【问题标题】:Python list comprehension or lambda possible for my given code snippet?对于我给定的代码片段,Python 列表理解或 lambda 可能吗?
【发布时间】:2022-01-09 04:22:58
【问题描述】:

编辑:删除未定义的变量。 所以我的代码基本上是尝试比较一个列表的值是否存在于另一个列表中。如果是这样,将值附加到第三个列表。如果该值不存在,则附加到第 4 个列表。执行此任务的最有效和最易读的方法是什么。我的代码示例:

a = [1,2,3]
b = [2,3,4,5,6,7]
c = []
d = []
for ele in a:
    if ele in b:
        c.append(ele )
    else:
        d.append(ele)

【问题讨论】:

  • gpu_value 来自哪里
  • 抱歉把gpu_value改成了ele,这是正确的

标签: python lambda list-comprehension


【解决方案1】:
a=[2,3,4,5]
b=[3,5,7,9]

c = [value for value in a if value in b] 
d = [value for value in a if value not in b]

print(f'Present in B: {c}')
print(f"Not present in B: {d}")

【讨论】:

    【解决方案2】:
    c = [i for i in a if i in b]
    
    d = [i for i in a if i not in b]
    

    【讨论】:

      【解决方案3】:

      解决这个问题的最好方法是使用集合。

      import random
      a = [random.randint(1, 15) for _ in range(5)]
      b = [random.randint(1, 15) for _ in range(7)]
      
      print(a)
      print(b)
      
      set_a = set(a)
      set_b = set(b)
      set_intersection = set_a.intersection(set_b)
      set_diff = set_a.difference(set_b)
      
      print(list(set_intersection))
      print(list(set_diff))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多