下面的代码读取文本文件(包含不同的数组) 分解成不同的元素。 我可以很好地处理带有两个子项的数组,但没有第三个子项。你知道吗
例如-此文件工作正常:
('January', 2, [('curly', 30), ('larry',10), ('moe',20)])
是的。你知道吗
staff = dict()
for item in filecontent:
month = filecontent[0]
section = filecontent[1]
for name, hours in filecontent[2]:
staff[name] = hours
print ("month:" + month)
print ("section: " + str (section))
print ("".join("%s has worked %s hours\n" % (name, hours) for name, hours in staff.items()))
overtime = int(input ("Enter overtime figure: "))
print ("".join("%s has now worked %s hours \n" % (name, (hours + overtime)) for name, hours in staff.items()))
但是我有一个不同的月份,有一个第三个数组元素(一个奖金数字),例如:
('February', 2, [('curly', 30, **10**), ('larry',10, **10** ), ('moe',20, **10**)])
下面是我修改上述代码的尝试,但不起作用。。。你知道吗
staff = dict()
for item in filecontent:
month = filecontent[0]
section = filecontent[1]
for name, hours, bonus in filecontent[2]:
staff[name] = hours, bonus
print ("month:" + month)
print ("section: " + str (section))
print ("".join("%s has worked %s hours with %s bonus \n" % (name, hours, bonus) for name, hours, bonus in staff.items()))
为什么不在应用算法之前检查元素的长度呢。 使用
len()
编辑 我建议如果你不想要这个解决方案,你可以让文件内容(如果你有控制权或你可以改变它)总是返回3个元素,其中0是默认值,如果你没有奖金。你知道吗
当您这样做时:
您正在创建元组:
所以当你做
staff.items()
的时候,结果就是[('john', (40, 10))]
。要打印此文件:*y
将展开(分解)元组传递给format函数,然后format函数将其映射到第二个和第三个参数。你知道吗相关问题 更多 >
编程相关推荐