【问题标题】:Checking if something is not in multiple lists - how to make it more elegant检查某些东西是否不在多个列表中 - 如何使其更优雅
【发布时间】:2018-12-05 22:53:41
【问题描述】:

什么有效:

a = ["0"]
b = ["1"]
c = ["2"]
d = ["3"]
if (not "0" in a) and (not "0" in b) and (not "0" in c) and (not "0" in 
d):
  print "you don't want this to be printing"

我尝试过但不起作用的方法:

if not "0" in (a and b and c and d):
  print ""

if not "0" in a, b, c, d:
  print ""

鉴于列表必须分开并且我有很多列表,我可以使用什么来避免我的第一个有效语句的不雅?

【问题讨论】:

    标签: python arrays list boolean


    【解决方案1】:

    为什么不简单地加入所有列表并进行检查:

    if "0" not in a + b + c + d:
        print("you don't want this to be printing")
    

    set 中尺寸列表的解决方案更快,这里有一些性能测试:

    In [1]: from random import randint
       ...: a = [str(randint(1, 1000)) for _ in range(500)]
       ...: b = [str(randint(1, 1000)) for _ in range(500)]
       ...: c = [str(randint(1, 1000)) for _ in range(500)]
       ...: d = [str(randint(1, 1000)) for _ in range(500)]
       ...: 
    
    In [2]: %timeit "0" not in a + b + c + d
    30.2 µs ± 265 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    
    In [3]: %timeit "0" not in set().union(a, b, c, d)
    48.5 µs ± 219 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    

    但是使用set 的解决方案节省了内存,因为a + b + c + d 生成了新的大列表。

    【讨论】:

    • 在这种情况下,没有任何冲突并且列表的大小很小。速度真的取决于数据本身。对于一个病态的例子,考虑 a 是 1000000000 "1" 的列表。您的建议可能会导致OOM! (在 那个 场景中,我的示例中的 #2 提供了最佳的内存效率。)
    • 基本上,如果不了解数据本身的结构,就无法衡量性能。
    • @MateenUlhaq 谢谢你的评论,关于记忆你是对的。对于中型列表,我编辑答案。对于大数据,认为这两种解决方案都不好。
    【解决方案2】:
    if not any(map(lambda x: "0" in x, [a, b, c, d])):
        print "you don't want this to be printing"
    

    这会将您的列表列表映射到您为每个列表重复的 lambda 函数,"0" in x,x 是 lambda 参数或列表。

    【讨论】:

    • 请在您的回答中添加一些文字描述......我们是人类。
    【解决方案3】:

    将所有内容放入列表中,然后使用all

    lists = [a, b, c, d]
    if all("0" not in x for x in lists):
        print("you don't want this to be printing")
    

    但使用德摩根定律和否定可能更快(更清晰):

    lists = [a, b, c, d]
    if not any("0" in x for x in lists):
        print("you don't want this to be printing")
    

    更快(最清晰):

    if "0" not in set().union(a, b, c, d):
        print("you don't want this to be printing")
    

    【讨论】:

      猜你喜欢
      • 2012-05-11
      • 2012-06-04
      • 2014-05-12
      • 1970-01-01
      • 2022-08-24
      • 1970-01-01
      相关资源
      最近更新 更多