Reputation: 1465
If I have a list of lists and just want to manipulate an individual item in that list, how would I go about doing that?
For example:
List1 = [[10,13,17],[3,5,1],[13,11,12]]
What if I want to take a value (say 50) and look just at the first sublist in List1
, and subtract 10 (the first value), then add 13, then subtract 17?
Upvotes: 67
Views: 493553
Reputation: 1
list1=[[1,2,3],[4,5,6],[7,8,9]]
to iterate over this list in O(n)
for ar in list1:
i=0
if i <len(ar)-1 :
print(arr[i])
Upvotes: -1
Reputation: 1
to print every individual element in double list
list1=[[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(list1)):
for j in range(len(list1[i])):
print(list1[i][j])
Upvotes: -1
Reputation: 566
new_list = list(zip(*old_list)))
*old_list unpacks old_list into multiple lists and zip picks corresponding nth element from each list and list packs them back.
Upvotes: -1
Reputation: 887
This code will print each individual number:
for myList in [[10,13,17],[3,5,1],[13,11,12]]:
for item in myList:
print(item)
Or for your specific use case:
((50 - List1[0][0]) + List1[0][1]) - List1[0][2]
Upvotes: 3
Reputation: 250881
You can use itertools.cycle
:
>>> from itertools import cycle
>>> lis = [[10,13,17],[3,5,1],[13,11,12]]
>>> cyc = cycle((-1, 1))
>>> 50 + sum(x*next(cyc) for x in lis[0]) # lis[0] is [10,13,17]
36
Here the generator expression inside sum
would return something like this:
>>> cyc = cycle((-1, 1))
>>> [x*next(cyc) for x in lis[0]]
[-10, 13, -17]
You can also use zip
here:
>>> cyc = cycle((-1, 1))
>>> [x*y for x, y in zip(lis[0], cyc)]
[-10, 13, -17]
Upvotes: 4
Reputation: 2476
for l in list1:
val = 50 - l[0] + l[1] - l[2]
print "val:", val
Loop through list and do operation on the sublist as you wanted.
Upvotes: 0
Reputation: 113930
List1 = [[10,-13,17],[3,5,1],[13,11,12]]
num = 50
for i in List1[0]:num -= i
print num
Upvotes: 2
Reputation: 39893
50 - List1[0][0] + List[0][1] - List[0][2]
List[0]
gives you the first list in the list (try out print List[0]
). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0]
.
Upvotes: 2
Reputation: 129477
You can access the elements in a list-of-lists by first specifying which list you're interested in and then specifying which element of that list you want. For example, 17
is element 2
in list 0
, which is list1[0][2]
:
>>> list1 = [[10,13,17],[3,5,1],[13,11,12]]
>>> list1[0][2]
17
So, your example would be
50 - list1[0][0] + list1[0][1] - list1[0][2]
Upvotes: 72