在字典中计算键中的字符数

2024-09-30 14:32:07 发布

您现在位置:Python中文网/ 问答频道 /正文

对于家庭作业,我已经设定了以下内容:

用myEmployees列表中的名字作为 为每个员工分配10000英镑的工资(作为价值)。查字典 增加四名以上员工的工资 名字长度为1000*的字母。先打印词典内容 在增加之后。在

我不知道怎么做。在

这就是我目前所想到的。在

employeeDict = {"John":'10,000', "Daren":"10,000", "Graham":"10,000", "Steve":"10,000", "Adren":"10,000"}

say = 'Before increase'
print say
print employeeDict

say1 = 'After increase'
print say1

for x in employeeDict:
x = len(employeeDict)
if x > 5:
    print employeeDict[x]

Tags: 内容列表字母员工名字john词典say
3条回答

这应该能满足你的需求。在

employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000}
print "Before increase"
print employeeDict

for name, salary in employeeDict.items():
    if len(name) > 4:
        employeeDict[name] = salary + len(name) * 1000
print "After increase"
print employeeDict

你的版本有些问题。在

  • for循环的标识不正确
  • 你得到的是字典的长度,而不是字典中键的长度。在
  • 你应该让字典中的值浮点数/整数。在

另外请注意,我相信你的作业中说如果名字的长度超过四个字符。所以我用了4而不是5。在

首先,将值更改为整数/浮点。在

employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000}

这样做之后,正如您所知道的,您需要循环检查dict中的条目

^{pr2}$

在上面的代码中,您的“x”将是员工姓名。如您所知,要将值赋给dict中的键,必须使用dict[key] = value,因此请尝试在if x > 5:block语句中执行该操作。我不是想给你一个完整的答案,而是想把你推向正确的方向。在

显然,你有一些缩进的问题,但是主要的问题是你用字典的长度(得到键的数量)而不是键的长度。你的逻辑也不好。在

employeeDict = {"John":'10,000', "Daren":"10,000", "Graham":"10,000", "Steve":"10,000", "Adren":"10,000"}

say = 'Before increase'
print say
print employeeDict

say1 = 'After increase'
print say1

for x in employeeDict:
    length = len(employeeDict)  # <---- indent this
    if length >= 5:    # <--- greater than 4
        # convert string to number, add money, convert back to string
        employeeDict[x] = str(int(employeeDict[x]) + 1000 * (length))

print employeeDict[x]

相关问题 更多 >