-1
爲什麼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
這不是一個列表理解。你可能需要'lst [[i for i in range(4)if i%2 == 0]]'。你的語法只是無效的Python。 –
我可以問你爲什麼使用numpy數組作爲字符串項?不是Numpy應該用於數字嗎? – tglaria
@tglaria我不使用它作爲字符串,這只是一個例子 –