python - reading an array with multiple items (working on two items not three) -
code below reads text file (containing different arrays) , breaks down separate elements. have working fine arrays 2 sub items, not third.
for example - file works fine:
('january', 2, [('curly', 30), ('larry',10), ('moe',20)])
.
staff = dict() item in filecontent: month = filecontent[0] section = filecontent[1] 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) name, hours in staff.items())) overtime = int(input ("enter overtime figure: ")) print ("".join("%s has worked %s hours \n" % (name, (hours + overtime)) name, hours in staff.items()))
but have different month third array element (a bonus figure), example:
('february', 2, [('curly', 30, **10**), ('larry',10, **10** ), ('moe',20, **10**)])
my attempt @ adapting above code below, not working...
staff = dict() item in filecontent: month = filecontent[0] section = filecontent[1] name, hours, bonus in filecontent[2]: staff[name] = hours, bonus print ("month:" + month) print ("section: " + str (section)) print ("".join("%s has worked %s hours %s bonus \n" % (name, hours, bonus) name, hours, bonus in staff.items()))
when this:
staff[name] = hours, bonus
you creating tuple:
>>> staff = {} >>> hours = 40 >>> bonus = 10 >>> name = 'john' >>> staff[name] = hours,bonus >>> staff[name] (40, 10)
so when staff.items()
result [('john', (40, 10))]
. print this:
print(''.join('{0} has worked {1} hours {2} bonus'.format(x, *y) x,y in staff.items()))
the *y
passes expanded (exploded) tuple format function, maps second , third arguments.
Comments
Post a Comment