【问题标题】:element comparison using list comprehension and conditions [closed]使用列表理解和条件进行元素比较[关闭]
【发布时间】:2019-12-28 12:04:50
【问题描述】:

表格中有两个列表:

a = [[x1, 1], [x2, 0], [x3, 4], [x4, 12], [x5, 15]]

b = [[x2, 10], [x3, 41], [x7, 50]]

我想我可以像下面这样来获取 ids x1、x2、x3 等等..

x = [item for item in b if item in a]

print(x)
[[x2, 10], [x3, 41]]

我实际上想打印 b 中 a 中的元素并比较它们的值

[x2, 10] -> [x2, 0]
[x3, 41] -> [x3, 4]

所以在上面的例子中只打印来自 if b[0][1] == 0 & a[1][1] != 0 的元素

任何帮助将不胜感激!

【问题讨论】:

  • 这种情况b[0][1] == 0 & a[1][1] != 0 是什么意思?
  • 两个列表中的x2,比较与x2关联的值
  • 您是否有任何理由尝试使用列表推导来执行此操作?对于复杂的标准,for 循环要容易得多。
  • @MisterMiyagi 你是对的,for 循环更容易解决。我是 Python 新手,所以虽然我可以使用列表推导从 b 中的 a 中查找值!

标签: python python-3.x for-loop list-comprehension


【解决方案1】:

您可能正在寻找这样的东西:

ax = [item[0] for item in a]
x = [item for item in b if item[0] in ax]
print x

【讨论】:

    【解决方案2】:

    list comprehensionenumerate 一起使用

    例如

    a = [['x1', 1], ['x2', 0], ['x3', 4], ['x4', 12], ['x5', 15]]
    b = [['x2', 10], ['x3', 41], ['x7', 50]]
    x = [a[index] for y in b for index,x in enumerate(a) if y[0] == x[0]]
    print(x)
    

    O/P:

    [['x2', 0], ['x3', 4]]
    

    【讨论】:

      【解决方案3】:

      您可以将a 转换为字典:

      adict = dict(a)
      

      然后我们就可以进行映射了:

      [[k, adict[k]] for k, __ in b if k in adict]
      

      【讨论】:

        【解决方案4】:

        你可以使用:

        a = [['x1', 1], ['x2', 0], ['x3', 4], ['x4', 12], ['x5', 15]]
        
        b = [['x2', 10], ['x3', 41], ['x7', 50]]
        
        a_dict = dict(a)
        
        print('    b           a')
        for x, val in b:
            if x in a_dict:
                print(f'[{x}, {val}] --> [{x}, {a_dict[x]}]')
        

        输出:

            b           a
        [x2, 10] --> [x2, 0]
        [x3, 41] --> [x3, 4]
        

        【讨论】:

        • 解决我的问题的最佳方法,谢谢!我可以在我想要的条件下再添加两个 if 语句!再次感谢
        【解决方案5】:

        你也可以使用python的operator模块。

        import operator
        
        getter = operator.itemgetter(0)
        c = [j for i in b for j in a if getter(i) == getter(j)]
        
        print(c)
        

        【讨论】:

          【解决方案6】:
          a = [['x1', 1], ['x2', 0], ['x3', 4], ['x4', 12], ['x5', 15], ['x7', 60]]
          
          b = [['x2', 10], ['x3', 41], ['x7', 50]]
          
          for x in b:
              if x[0] in dict(a):
                  v = dict(a)[x[0]]
                  if x[1] > v:
                      print('{} -> {}'.format(x, [x[0], v] ))
                  else:
                      print('{} -> {}'.format([x[0], v] , x))
          

          输出

          ['x2', 10] -> ['x2', 0]
          ['x3', 41] -> ['x3', 4]
          ['x7', 60] -> ['x7', 50]
          

          【讨论】:

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