读取包含多个项目的数组(处理两个项目而不是三个项目)

时间:2013-08-07 19:07:37

标签: python arrays python-3.x tuples

下面的代码从文本文件中读取(包含不同的数组) 并分解为单独的元素。 我对包含两个子项的数组工作得很好,但不是第三个。

例如 - 此文件正常工作:

('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()))

2 个答案:

答案 0 :(得分:3)

执行此操作时:

staff[name] = hours, bonus

你正在创建一个元组:

>>> staff = {}
>>> hours = 40
>>> bonus = 10
>>> name = 'john'
>>> staff[name] = hours,bonus
>>> staff[name]
(40, 10)

因此,当您执行staff.items()时,结果为[('john', (40, 10))]。打印这个:

print(''.join('{0} has worked {1} hours with {2} bonus'.format(x, *y) for x,y in staff.items()))

*y将展开的(爆炸的)元组传递给format函数,然后将其映射到第二个和第三个参数。

答案 1 :(得分:0)

为什么不在应用算法之前检查元素的长度。 使用len()

for element in filecontent[2]:
   if len(element) == 3:
      name, hours, bonus = element
      ## do other stuff

   else: 
      name, hours = element

修改 我建议如果你不想要这个解决方案,你可以拥有文件内容(如果你可以控制它或者你可以改变它)总是返回3个元素,如果没有奖金,则默认为0。