This is what I have:
mylist1 = [[1,2,3], [4,5,6], [7,8,9]]
for i in mylist1:
if i[0] % 2 == 0:
print(i[0])
if i[1] % 2 == 0:
print(i[1])
if i[2] % 2 == 0:
print(i[2])
Is there a shorter way?
This is what I have:
mylist1 = [[1,2,3], [4,5,6], [7,8,9]]
for i in mylist1:
if i[0] % 2 == 0:
print(i[0])
if i[1] % 2 == 0:
print(i[1])
if i[2] % 2 == 0:
print(i[2])
Is there a shorter way?
List comprehension?
print('\n'.join(str(i) for sublist in mylist1 for i in sublist if i % 2 == 0))
Less hardcore list comprehension?
for sublist in mylist1:
print('\n'.join(i for i in sublist if i % 2 == 0))
For loop?
for sublist in mylist1:
for i in sublist:
if i % 2 == 0:
print(i)
You can use filter with itertools' chain.from_iterable
:
from itertools import chain
mylist1 = [[1,2,3], [4,5,6], [7,8,9]]
print(list(filter(lambda x: x % 2 == 0, chain.from_iterable(mylist1))))
# [2, 4, 6, 8]
You can use a nested loop try this.
mylist1 = [[1,2,3], [4,5,6], [7,8,9]]
for i in mylist1:
for j in i:
if j % 2 == 0:
print(j)
If you know the format is going to be a list of lists, I suppose you could just use nested for loops
mylist1 = [[1,2,3], [4,5,6], [7,8,9]]
for x in mylist1:
for y in x:
if y%2 == 0:
print(y)
Unless you're asking it to be quicker in terms of CPU time in which case I would probably use numpy. Keep experimenting bud!
You can just pass *param
to chain
:
from itertools import chain
[i for i in chain(*mylist1) if i % 2 == 0]
Yet another option, a one-liner that uses no imports:
print(*[val for lst in mylist1 for val in filter(lambda x: x & 1 == 0, lst)])
Or if having them on separate lines is important:
print(*[val for lst in mylist1 for val in filter(lambda x: x & 1 == 0, lst)], sep = "\n")