Reputation: 987
say I have this list of list
listlist = [[0,0,0,1],[0,0,1,1],[1,0,1,1]]
and a empty dict()
answer = dict()
and say I want to find the leftmost non-zero in each list such that I can save the index of that non-zero number into a dictionary like:
for list in listlist: #(this is how the first iteration would look like:)
answer[0] = 3
next iteration
answer[1] = 2
next iteration
answer[2] = 0
I am pretty new at programming, so excuse me if it is trivial, I have tried different stuff and it is hard to find out how to do this.
Upvotes: 2
Views: 358
Reputation: 17991
Assuming only 0
s and 1
s this should work
i = 0
for mylist in listlist:
answer[i] = mylist.index(1)
i += 1
I recommend that you do not name your list list
, that overrides some functionality. I prefer to default to the variable name mylist
Upvotes: 4
Reputation: 26407
If it's only ever 0
s and 1
s just do something like,
>>> answer = {i: lst.index(1) for i, lst in enumerate(listlist)}
>>> answer
{0: 3, 1: 2, 2: 0}
Also, don't use list
as a variable name since it will mask list
built-in.
Upvotes: 8
Reputation: 913
listlist = [[0,0,0,1],[0,0,1,1],[1,0,1,1]]
answer = dict()
for idx,alist in enumerate(listlist):
for i in range(len(alist)):
if alist[i] > 0:
answer[idx] = i
Upvotes: 2