2013-08-07 16 views
0

下面的代碼從文本文件(包含不同的數組) 中讀取並分解爲單獨的元素。 我有它與兩個子項目的數組,但沒有第三個正常工作。讀取具有多個項目的數組(在兩個項目上工作而不是三個)

例如 - 該文件正常工作:

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

回答

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經過膨脹(分解)元組的格式的功能,然後將其映射到第二和第三個參數。

0

爲什麼不在應用算法之前檢查元素的長度。 使用len()

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

    else: 
     name, hours = element 

編輯 我建議,如果你不希望這個解決方案,你可以有文件內容(如果你有控制權,否則,你可以改變它)總是返回3個元素,其中0如果你沒有獎金,這是默認的。

相關問題