Reputation: 1
transfers = [['owen', 'susan', '10'], ['owen', 'robert', '10'], ['owen','drew', '10'], ['fred', 'owen', '20']]
people = ['drew', 'fred', 'owen', 'robert', 'susan']
bals = [0]*len(people)
for p in people:
bals[k for k in range(len(people))] = [i[2] for i in transfers if p in i]
^
SyntaxError: invalid syntax
Why am I getting this error?
i[2] for i in transfers should be the numbers in the lists of "transfers", and I only want it to be the numbers from the lists that contain the name of the certain person (p) in the loop.
Upvotes: 0
Views: 46
Reputation: 1471
It should be
for i, p in enumerate(people):
bals[i] = [t[2] for t in transfers if p in t]
Or,
bals = [[t[2] for t in transfers if p in t] for p in people]
Your code does not work because list subscription does not accept list comprehension.
In addition, list subscription does accept generator
. Putting list comprehension inside parenthesis makes a generator. A correct code in terms of syntax could be bals[(k for k in range(len(people)))]
where in the middle it is a generator
object. But generator still won't work with list and therefore is a TypeError
.
Upvotes: 3