0

ファイルにデータがあり、2 セットの値と不特定の一連の配列 (それぞれに 3 つのサブ項目があります) があります。

例えば:

('January', 2, [('curly', 30), ('larry',10), ('moe',20)])

データを読み取って提示し、データを新しい変数に部分的に再割り当てする必要があります。

例えば:

Month: January
Section: 3 
curly has worked 30 hours 
larry has worked 10 hours 
moe has worked 20 hours 

文字列の最初の 2 つの部分を読み取ることはできますが、配列を分割する方法がわかりません。各ファイルには異なる数のサブ配列がある可能性があるため、while ループのようにする必要がありますか?

import ast 

filecontent = ast.literal_eval(filename.read())

for item in filecontent:
    month = filecontent[0]
    section = filecontent[1]

    name1 = filecontent[2] # not working
    hours1 = filecontent[3]# not working
    name2 = filecontent[4]# not working
    hours2 = filecontent[5]# not working
    # account for additional arrays somehow?

print ("month:" + month)
print ("section" + str (section))
print (str (name1) + "has worked"  + str (hours1))
print (str (name2) + "has worked"  + str (hours2))
4

5 に答える 5

0

justin が示唆したように、filecontent の 3 番目の項目を反復処理する必要があります。つまり、filecontent を反復処理します[2]。

于 2013-08-07T11:48:06.780 に答える
0

filecontent を item で繰り返しますが、item はまったく使用しません。一つ間違いがあると思います。filecontent[0] の代わりに item[0]、filecontent[1] の代わりに item[1] などを使用する必要があるかもしれません。

于 2013-08-07T11:38:43.623 に答える