簡體   English   中英

列表理解在python中不起作用

[英]List comprehension not working in python

好的,所以這段代碼對我來說很好用。

a = [1, 2, 3, 4]
c = ['Three' if i is 3 else "Not Three" for i in a]
print(c)

輸出:

['Not Three', 'Not Three', 'Three', 'Not Three']

但是,做同樣的事情稍微復雜一點,此代碼不起作用。 我在哪里想念什么?

import numpy as np

# 2 random np array of 10 elements ranging from -1 to 1
x = np.random.rand((10))*2 - 1
y = np.random.rand((10))*2 - 1

# xor = x>0 and y>0 or x<=0 and y<=0
xor = np.logical_or(
    np.logical_and(
        np.greater(x, 0), 
        np.greater(y, 0)), 
    np.logical_and(
        np.less_equal(x, 0), 
        np.less_equal(y, 0))
)
print(xor) # prints an array of random true and false of shape 200 

colors = np.array(['blue' if i is True else 'red' for i in xor])
# should print array of 'blue' and 'red' according to xor. But prints all 'red'
print(colors)

輸出:

[ True  True False False  True  True  True False False  True]
['red' 'red' 'red' 'red' 'red' 'red' 'red' 'red' 'red' 'red']

不使用的is

colors = np.array(['blue' if i else 'red' for i in xor])

問題是您的xor列表不是bool列表

在循環中顯示i的類型可提供以下結果:

print([type(i) if i == True else type(i) for i in xor])

[<class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>, <class 'numpy.bool_'>]

您使用關鍵字任何時候is該項目必須是針對被比較准確的項目。 在Python環境中, True值只有一個。 一個is比較的可變反對真正的一個值進行比較。

在您的情況下,變量i從未真正為True ,它是具有某些值的numpy布爾值。
==比較將在評估==的每一面時起作用,最后進行布爾到布爾比較。

但是,如前所述,首選形式根本沒有可比性。 if i是你想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM