在搜索字符串时,如何从列表列表中返回列表,并强制将比较与小写列表?

发布于 2025-01-29 13:00:56 字数 518 浏览 2 评论 0原文

我有这样的列表:

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']

我基本上会在列表列表中查找用户的请求单词,如果有匹配项,我会打印该列表。在上面的情况下,用户搜索“切尔西”,在其中一个列表中,“切尔西”(切尔西FC或切尔西都没有关系)。因此,我将返回该特定列表。

我尝试使用“任何”,但它似乎只返回布尔值,而我实际上无法从中打印任何列表。

I have a list of lists as such:

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']

I would basically look for the user's requested word in a list of lists, and if there's a match, I print that list. In the case above, the user searches for "chelsea" and in one of the lists, there's a match for "chelsea" (either Chelsea FC or Chelsea, doesn't matter). So I would return that specific list.

I tried using "any" but it seems to only return a boolean and I can't actually print any list from it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

腻橙味 2025-02-05 13:00:56

您可以使用列表理解:

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']]

You can use a list comprehension:

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())
]

output:

[[61, 'Chelsea FC', 'Chelsea', 'CHE']]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文