I have list in shape a = [[aaa,1,0],[aba,1,2],[aca,0,3],...]
. By using a list comprehension I'd like to compose a new list if the second element of a row is equal to lets say 1.
For now b = [x[1]==1 for x in a]]
returns a boolean true
false
but I want those indexes return a new list.
Asked
Active
Viewed 1,416 times
0

Arkistarvh Kltzuonstev
- 6,824
- 7
- 26
- 56

colt.exe
- 708
- 8
- 24
-
3So use a [Conditional expression](https://docs.python.org/3/reference/expressions.html#conditional-expressions) instead? – yatu Apr 28 '20 at 11:11
-
you create wron list comprehension - you have to use `if` inside it. – furas Apr 28 '20 at 11:12
4 Answers
2
try:
a = [[aaa,1,0],[aba,1,2],[aca,0,3],...]
output = [i for i in a if i[1] == 1]
or you can use filter
which returns an iterator:
output = filter(lambda x: x[1] == 1, a)

Gabio
- 9,126
- 3
- 12
- 32
1
Try this :
b = [i for i,j in enumerate(a) if j[1]==1]
It gives you the a list of indexes for which second item equals to 1
. If you want to get a list of items of which second item is equal to 1
,try this :
b = [i for i in a if i[1]==1]
If you want a slightly speedier version, use filter method :
b = filter(lambda i: i[1]==1, a)

Arkistarvh Kltzuonstev
- 6,824
- 7
- 26
- 56
1
I guess, this is the syntax you are looking for:
b = [x for x in a if x[1]==1]

AnsFourtyTwo
- 2,480
- 2
- 13
- 33
1
b = [ i for i,item in enumerate(a) if a[i][1]==1]
This will return a list containing indices of element in a , that satisfies the condition
if u want the items itself make it
b = [item for i,item in enumerate(a) if a[i][1]==1]

Sruthi
- 54
- 6