2 回答

TA貢獻2037條經驗 獲得超6個贊
我希望能夠查看一個字符串是否在我的列表中,然后打印列表中包含該字符串的所有項目。
我發現[s for s in y if any(xs in s for xs in topcolour)]使用它,當我只在列表中查找數字時,這非常有效,但是當我嘗試查找顏色(藍色、紅色、黃色或綠色)時,它告訴我可以找到顏色,然后打印出整個列表而不是列表中的單個項目,就像對數字所做的那樣。僅供參考 p1card,topnumber 和 topcolour 每場比賽都會改變。
if any(topnumber in s for s in p1cards):
matching = [s for s in p1cards if any(xs in s for xs in topnumber)]
print(matching) #this one works
elif any(topcolour in s for s in p1cards):
matching = [s for s in p1cards if any(xs in s for xs in topcolour)]
print(matching) #this one doesn't work
如果可以找到第一個代碼塊,則輸出列表中的確切項目,例如["Blue 7"],如果 topnumber 為 7,但當我嘗試按顏色搜索時,它只會輸出整個列表。

TA貢獻1865條經驗 獲得超7個贊
如果沒有明確的輸入和輸出示例,很難判斷這是否正是您想要做的,但我認為它可以根據您提供的內容起作用。
我個人發現嵌套理解真的很難閱讀,你不需要它們。是檢索滿足特定條件的集合成員的filter一個很好的函數方法。lambda不是必需的——你可以定義單行函數并將它們作為第一個參數傳遞——但這對于像這樣的非常簡單的測試很有用。
p1cards = {'Pick colour', 'Red 1', 'Yellow 5', 'Red 9', 'Blue skip', 'Blue 6'}
topnumber = '9'
print(tuple(
filter(
lambda c: topnumber in c,
p1cards,
)
))
topcolour = 'Red'
print(tuple(
filter(
lambda c: topcolour in c,
p1cards,
)
))
輸出:
('Red 9',)
('Red 1', 'Red 9')
注意:tuple來電僅供展示。如果您在 Python 2.x 中運行它,則不需要它們;在 3.x 中,沒有它們您將無法獲得有用的輸出。
添加回答
舉報