简体   繁体   中英

Using both if and for in list comprehension

I have an array, a=[1,2,3,4,5,6,7], and I am trying to find the index of all the values which are less than 6 and greater than 2, using list comprehension. I am using the following technique:

tk = [b if (a[b]>=2 & [b]<=6) for b in range(len(a))]

It keeps saying that there is a syntax error at 'for'. Any idea how to resolve this? Or what am I doing wrong?

This should be enough to do the trick:

>>> indices = [i for i, x in enumerate(a) if 2 < x < 6]
>>> indices
[2, 3, 4]

Below code will work

  tk = [b for b in range(len(a)) if (a[b]>= 2 and a[b] <= 6)]
  tk
  [1, 2, 3, 4, 5]

I have modified 3 things here:

  1. way we should call list comprehension with if condition
  2. rather than using [b] used a[b]
  3. used and rather than &

Hope this will help

The placement of the condition in a comprehension has always been a point of much confusion to me as well, so I came up with a working mnemonic device.

If you are excluding elements from the list, if belongs to the loop, and goes after the for :

[item for item in items ]

If you are deciding between values, that's just a normal ternary operator , which appears as part of the comprehension before the for :

[ for item1, item2 in items]

Your case is clearly the first one since you are excluding elements. The test should therefore go after the for , with appropriate syntax fixes:

tk = [b for b in range(len(a)) ]

It might be more intuitive to implement the same operation using enumerate to get the indices instead of range :

tk = [item for index, item in enumerate(a) if 2 <= index <= 6]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM