我有一個這樣的串列串列:
allTeams = [ [57, 'Arsenal FC', 'Arsenal', 'ARS'], [58, 'Aston Villa FC', 'Aston Villa', 'AVL'], [61, 'Chelsea FC', 'Chelsea', 'CHE'], ...]
userIsLookingFor = "chelsea"
for team in allTeams:
if userIsLookingFor.lower() in any_element_of_team.lower():
print(team)
> [61, 'Chelsea FC', 'Chelsea', 'CHE']
我基本上會在串列串列中查找用戶請求的單詞,如果有匹配項,我會列印該串列。在上面的例子中,用戶搜索“chelsea”并在其中一個串列中找到“chelsea”的匹配項(Chelsea FC 或 Chelsea,無關緊要)。所以我會回傳那個特定的串列。
我嘗試使用“any”,但它似乎只回傳一個布林值,我實際上無法從中列印任何串列。
uj5u.com熱心網友回復:
您可以使用串列推導:
userIsLookingFor = "chelsea"
# option 1, exact match item 2
[l for l in allTeams if l[2].lower() == userIsLookingFor]
# option 2, match on any word
[l for l in allTeams
if any(x.lower() == userIsLookingFor
for s in l if isinstance(s, str)
for x in s.split())
]
輸出:
[[61, 'Chelsea FC', 'Chelsea', 'CHE']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478297.html
上一篇:將串列與輸入進行比較
