I’m struggling on how to select items at the same index from two sublists using zip function
List1 = [ [ 6, 7, 8 ] , [ 9, 10, 11 ] ]
List2 = [ [ A, B, C ] , [ D, E, F ] ]
for i, j in zip(List1, List2):
out1 = [ ]
out2 = [ ]
for c, v in zip( range(len(i)), range(len(j))):
# I'm struggling here
if c =1 and v = 1:
out1.append( c[i] )
out2.append( v[j] )
Expect result:
out1 = [7, 10]
out2 = [ ]
6
I think you want something like this? just take index 1 of each list, you don’t need to do a second inner iteration. You also need to take care of the scope/indentation of out1
/out2
, with the current code it is essentially resetting those two output variables on every sublist instead of being something added to during each iteration. You also might want to do something like checking each inner list is at least of length 2, but that’s just another inner list.
List1 = [[6, 7, 8], [9, 10, 11]]
List2 = [["A", "B", "C"], ["D", "E", "F"]]
out1 = []
out2 = []
for a, b in zip(List1, List2):
out1.append(a[1])
out2.append(b[1])
output:
>>> out1
[7, 10]
>>> out2
['B', 'E']
You can also do this with list comprehensions
out3 = [sublist[1] for sublist in List1]
out4 = [sublist[1] for sublist in List2]
output:
>>> out3
[7, 10]
>>> out4
['B', 'E']