我在学校被困在这个问题上的时间已经超过了我想承认的时间.我已经做了5次不同的迭代来解决这个问题,最近的一次是在这个问题下面。这是为了我要上的一堂课。
提供了以下员工和薪资字典,创建一个个性化的薪资信息,让每个员工都知道他们已经得到了2%的加薪和新的工资总额。
预期成果:
约翰,你现在的薪水是54000.00。你得到2%的加薪。这意味着你的新薪水是55080.0朱迪,你现在的薪水是71000.00。你得到2%的加薪。这意味着你的新薪水是72420.0阿尔伯特,你现在的薪水是38000.00。你得到2%的加薪。这使你的新工资38760.0阿方佐,你目前的工资是42000.00。你得到2%的加薪。这使你的新薪水达到42840.0。
employeeDatabase = {
'John': 54000.00,
'Judy': 71000.00,
'Albert': 38000.00,
'Alfonzo': 42000.00
}我的许多尝试之一(我现在意识到我应该保存以前的尝试,我只是使用一个随机的在线IDE):
newdict = employeeDatabase.copy()
for x in newdict:
newsal = newdict[x]
newsal = newsal *.02 + newsal
for i in employeeDatabase:
print (i + ' your current salary is %s You received a 2%% raise. This makes your new salary %d' % (employeeDatabase[i], newsal))发布于 2020-05-19 15:35:05
您不需要在其中使用newdict,只需使用items获取名称和薪资,然后打印这2个值加上增加的值。我也将其更改为使用新的字符串格式语法,因为旧的%样式已不再使用:
for employee, salary in employeeDatabase.items():
print ("{}, your current salary is {:.2f}. You received a 2% raise. This makes your new salary {:.2f}".format(employee, salary, salary * 1.02))发布于 2020-05-19 15:46:14
由于dict结构,您可以使用键更改数据,因此:
employeeDatabase = {
'John': 54000.00,
'Judy': 71000.00,
'Albert': 38000.00,
'Alfonzo': 42000.00
}
employeeDatabase['John'] = 58000.00现在约翰的薪水是58000
若要将所有雇员的工资提高2%,请做以下工作:
def raise_salary(employeers):
for i in employeers.keys():
print(f'{i} your current salary is {employeers[i]} You received a 2% raise. This makes your new salary {employeers[i] + employeers[i] *.02}')注意:我使用的是f字符串,这适用于python3.6+
发布于 2020-05-19 17:38:09
您可以在python中使用dict对象的函数.items()。我给您返回一个键值对,您可以使用for-循环进行迭代。此外,通过使用String函数.format(),您可以使用默认消息设置一个变量,然后填充特定的值(名称、工资等)。在for-循环中
message = '{}, your current salary is {}. You received a 2% raise. This makes your new salary {}'
employeeDatabase = {
'John': 54000.00,
'Judy': 71000.00,
'Albert': 38000.00,
'Alfonzo': 42000.00
}
for employee, salary in employeeDatabase.items():
print(message.format(employee, salary, salary * 1.02))变量{}中的message指示要使用dict中的信息自定义默认信息的位置。
https://stackoverflow.com/questions/61894824
复制相似问题