我試圖找到一個字串Date是否存在于一個專案的串列中。如果Date不存在,我想得到一個空串列。
代碼
data = [['Organization', 'Name', 'San Franciso', 11, 32] 。
['CreativeTeamRoles', 'Description', 'Music Director', 945, 959] 。
['Person', 'FullName', 'Salonen', 5761, 5778] 。
['CreativeTeamRoles', 'Description', 'Conductor', 7322, 7331] 。
['SoloistRoles', 'Description', 'Piano', 7627, 7632] 。
['Performances', 'Starttime', '2:00PM', 8062, 8068] 。
['Performances', 'Date', '2021-05-07', 8247, 8252] 。
['Performances', 'Endtime', '7:30PM', 8262, 8268] ]
output_list = [專案 for items in data for items in items if 'Date' in item]
因為它既有字串又有整數,所以我得到了一個錯誤
TypeError: argument of type 'int'/span> is not iterable
uj5u.com熱心網友回復:
試試這個:
[d for d in data if 'Date' in d]
uj5u.com熱心網友回復:
從問題上看,
看來你想要的是一個嵌套串列中給定字串存在的布林值,你可以這樣嘗試,它只回傳True和False
print(any([True for i in data if 'Data' in i else False] ))
如果你想要包含給定字串的串列,那么 -
print([*i for i in data if 'Data' in i] )
告訴我這對你來說是否合適......
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/333355.html
標籤:
