[英]Comparison of list to list of lists and return the other element from the list of list
[英]How can I return a list from a list of lists when searching a string and also force the comparison to lowercase?
我有一個這樣的列表列表:
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”,但它似乎只返回一個布爾值,我實際上無法從中打印任何列表。
您可以使用列表推導:
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']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.