0

我在一个文件中有数据,该文件有两组值,然后是一组未指定的数组(每个数组中有 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 

我可以读取字符串的前两部分,但不知道如何分解数组- 每个文件可能有不同数量的子数组,所以需要像 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

您需要遍历序列中的第三项。

for item in filecontent:
    print 'Month %s' % item[0]
    print 'Section %d' % item[1]

    for name, hours in item[2]:
        print "%s has worked %d hours" % (name, hours)
于 2013-08-07T11:37:20.743 回答
0

您使用 item 迭代文件内容,但您根本不使用 item。我认为有一个错误。也许你应该使用 item[0] 而不是 filecontent[0], item[1] 而不是 filecontent[1] 等等

于 2013-08-07T11:38:43.623 回答
0

正如贾斯汀建议的那样,您必须遍历文件内容中的第三项:即遍历文件内容[2]

于 2013-08-07T11:48:06.780 回答
0

我现在需要弄清楚如何读取和处理数组中的附加项。例如,奖金的新数字

文件内容 = [('January', 2, [('curly', 30, 5 ), ('larry',10, 5 ), ('moe',20, 10 )])]

下面的代码可以正常工作,并允许用户根据数据进行计算。我现在需要添加第三个数字。然后项目完成。

filecontent = [('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()))

我试过这个;

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()))
于 2013-08-07T12:46:53.393 回答
0

您可以使用字典来存储您的工人。 编辑

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

workers = dict()
month = ""
section = ""
for w in work:
    month = w[0]
    section = w[1]
    for worker, time, overtime in w[2]:
        workers[worker] = (time, overtime)
    print "Month: {0}\nSection: {1}".format(month, section)
    print "".join("%s has worked %s hours, overtime %s\n" % (worker, time[0], time[1]) for worker, time in workers.items())
于 2013-08-07T14:28:02.430 回答