为什么numpy数组可以通过列表索引,但不能通过列表推导索引?
lst = np.array(lst = ["a","b","c","d"])
ind = [i for i in range(4) if i%2 == 0]
# Indexing by the list works
lst[ind]
Out[28]:
array(['a', 'c'],
dtype='|S1')
# Trying to use the list comprehension without storing it in an object first does not
lst[i for i in range(4) if i%2 == 0]
File "<ipython-input-29-6256b805fa19>", line 1
lst[i for i in range(4) if i%2 == 0]
^
SyntaxError: invalid syntax
答案 0 :(得分:1)
您只需要一组额外的括号来“包含”列表理解:
lst[[i for i in range(4) if i%2 == 0]]