【问题标题】:How can I return True if x is in either of multiple lists?如果 x 在多个列表中的任何一个中,我如何返回 True?
【发布时间】:2014-07-12 06:39:02
【问题描述】:
>>> list1 = ['yes', 'yeah']
>>> list2 = ['no', 'nope']
>>> 'no' in list2
True
>>> 'no' in list1
False
>>> 'no' in (list1, list2)
False
>>> 'no' in (list1 and list2)
True
>>> 'yes' in (list1 and list2)
False #want this to be true
>>> 'yes' in (list1 or list2)
True
>>> 'no' in (list1 or list2)
False #want this to be true
>>>

如你所见,我无处可去。

如果 x 或 y 在任一列表中,我怎样才能使它返回 true?

【问题讨论】:

  • 我认为将上面使用的所有右手参数输入 python 解释器以查看它们返回的内容对您非常有帮助。这可能有助于您理解为什么这些方法都不起作用。

标签: python list return


【解决方案1】:

您可以使用any

>>> any('yes' in i for i in (list1, list2))
True

或者,只是连接列表:

>>> 'yes' in list1+list2
True

【讨论】:

  • 我是一个该死的白痴,因为我没有考虑连接。谢谢!
  • @Peaser,没问题。很高兴我能帮上忙
【解决方案2】:

使用any function

>>> any('no' in x for x in (list1, list2))
True

【讨论】:

    【解决方案3】:

    我认为这里简洁的代码和效率之间的最佳平衡可能是使用itertools.chain

    import itertools
    'no' in itertools.chain(list1, list2)
    

    chain 函数返回一个迭代器,它连续生成每个列表的值。结果类似于将所有列表连接在一起,但不会增加实际创建一个庞大列表的开销。

    另一个不错的功能是您可以将列表列表传递给chainunpack it with the * operator

    all_lists = [list1, list2]
    'no' in itertools.chain(*all_lists)
    

    【讨论】:

    • 您应该使用itertools.chain.from_iterable(all_lists),而不是itertools.chain(*all_lists)
    • @SvenMarnach - 我在文档中看到了这一点(以前从未使用过),但它似乎只是为了支持无限迭代器而添加的。否则会有显着的性能差异吗?我只是偶尔使用 Python,但如果没有严重的性能影响,似乎坚持使用 * 会更“pythonic”。
    • 使用* 强制立即评估外部迭代器。使用itertools.chain.from_iterable() 懒惰地评估一切。对于应该在通用迭代器上工作的代码,这是可取的。如果你知道你是在中型列表上操作,那并不重要。
    【解决方案4】:

    any一般是这样的,不过也有这个简单的表达方式:

    >>> x = 'yes'
    >>> (x in list1) or (x in list2)
    True
    >>> x = 'yep'
    >>> (x in list1) or (x in list2)
    False
    

    如果xlist1 中,这具有对表达式进行快捷评估的好处,而any 方法每次都会遍历这两个列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 2011-04-15
      • 2021-05-27
      • 2020-01-20
      • 2016-03-24
      • 1970-01-01
      • 2021-03-11
      相关资源
      最近更新 更多