我在一个文件中有数据,该文件有两组值,然后是一组未指定的数组 (每个中有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
我可以得到字符串读取的前两部分,但不知道如何打破数组 - 每个文件可能有不同数量的子数组,所以需要同时做循环?
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))
答案 0 :(得分: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)
答案 1 :(得分:0)
您使用item迭代filecontent,但根本不使用item。我认为有一个错误。也许您应该使用item [0]而不是filecontent [0],item [1]而不是filecontent [1]等等
答案 2 :(得分:0)
就像贾斯汀建议的那样,你必须遍历filecontent中的第三项:即迭代文件内容[2]
答案 3 :(得分:0)
我现在需要弄清楚如何阅读和处理数组中的其他项目。 例如,奖金的新数字
filecontent = [('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()))
答案 4 :(得分: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())