检查列表中的字符串部分是否存在于另一个列表中

发布于 2025-02-09 20:42:53 字数 337 浏览 1 评论 0原文

我有以下列表:

x1 = ['Apples:Red',
      'Apples:Green',
      'Bananas:Yellow',
      'Grapes:Purple',
      'Grapes:Green']
x2 = ['Green', 'Yellow']

我想检查列表中的冒号之后的子弦x1x2中的任何字符串匹配。

寻找这样的输出:

['Apples:Green',
 'Bananas:Yellow',
 'Grapes:Green']

I have the following lists below:

x1 = ['Apples:Red',
      'Apples:Green',
      'Bananas:Yellow',
      'Grapes:Purple',
      'Grapes:Green']
x2 = ['Green', 'Yellow']

I would like to check if the substring after the colon in list x1 matches with the any of the strings in x2.

Looking for an output like this:

['Apples:Green',
 'Bananas:Yellow',
 'Grapes:Green']

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

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

发布评论

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

评论(2

如梦初醒的夏天 2025-02-16 20:42:53

您可以做这样的事情(RHS =右侧):

x1 = ['Apples:Red', 'Apples:Green', 'Bananas:Yellow', 'Grapes:Purple', 'Grapes:Green']

x2 = ['Green', 'Yellow']


list_new = []
for substring in x1:
    rhs = substring.split(":")[1]
    if rhs in x2:
        list_new.append(substring)

>>> list_new
['Apples:Green', 'Bananas:Yellow', 'Grapes:Green']

You can do something like this (rhs = right-hand side):

x1 = ['Apples:Red', 'Apples:Green', 'Bananas:Yellow', 'Grapes:Purple', 'Grapes:Green']

x2 = ['Green', 'Yellow']


list_new = []
for substring in x1:
    rhs = substring.split(":")[1]
    if rhs in x2:
        list_new.append(substring)

>>> list_new
['Apples:Green', 'Bananas:Yellow', 'Grapes:Green']
眼角的笑意。 2025-02-16 20:42:53

如果x2以任何重要的方式很重要,请在进行查找之前将其转换为set

s2 = set(x2)

列表理解应该做:

[x for x in x1 if x.split(':', 1)[-1] in s2]

通过maxSplit = 1str.split确保仅第一个导致拆分。

If x2 is in any way significant, turn it into a set before doing lookups:

s2 = set(x2)

A list comprehension should do the rest:

[x for x in x1 if x.split(':', 1)[-1] in s2]

Passing maxsplit=1 to str.split ensures that only the first : results in a split.

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