【问题标题】:Python, in a list of lists compare first element of the first list to the first element of the second listPython,在列表列表中将第一个列表的第一个元素与第二个列表的第一个元素进行比较
【发布时间】:2012-11-05 18:43:44
【问题描述】:

所以我有这个:

a = [[4, 8], [5, 6, 9, 10], [13]]

我想得到以下之间的差异(减法):

4 - 5 = a[0][0] - a[1][0]

4 - 6 = a[0][0] - a[1][1]

4 - 9 = a[0][0] - a[1][2]

4 - 10 = a[0][0] - a[1][3]

然后转到8:

8 - 5 = a[0][1] - a[1][0]

8 - 6 = a[0][1] - a[1][1]

...

所有子列表以此类推

有什么想法吗?

编辑:其他比较看起来像这样:

5 - 13 = a[1][0] - a[2][0]

6 - 13 = a[1][1] - a[2][0]

9 - 13 = a[1][2] - a[2][0]

10 - 13 = a[1][3] - a[2][0]

因为这是倒数第二个列表,所以它会停止。

我正在尝试实现 Quine-McCluskey 方法以最小化逻辑表达式。

【问题讨论】:

  • 您能否更准确地说明“所有子列表的等等”的含义?您想要 5、6、9、10 和 13 中的每一个之间的差异吗?

标签: python list subtraction


【解决方案1】:

假设在完成a[0][1] - a[1][x]之后你想继续a[0][0] - a[2][0],然后最终也做a[1][0] - a[2][0]等:

result = []
for i, sub_x in enumerate(a[:-1]):
    for sub_y in a[i+1:]:
        for x in sub_x:
            result.append([x - y for y in sub_y])

>>> result
[[-1, -2, -5, -6], [3, 2, -1, -2], [-9], [-5], [-8], [-7], [-4], [-3]]

作为列表理解:

[[x - y for y in sub_y]
     for i, sub_x in enumerate(a[:-1]) for sub_y in a[i+1:] for x in sub_x]

【讨论】:

  • 非常感谢!这正是我所需要的。很抱歉,我没有明确说明我想将第二个列表与第三个列表进行比较,很高兴你知道了!
  • 列表推导的外循环迭代 a[i+1:],这与扩展 sn-p 中的 a[:-1] 上的外循环不同。这是故意的吗?这不会产生不同的结果吗?
【解决方案2】:

这样的东西可以满足你的要求,

但我不知道您还需要哪些进一步的迭代,因为这个问题很模糊。你用 13 做什么?

>>> from itertools import product
>>> [i[0] - i[1] for i in product([4, 8], [5, 6, 9, 10])]
[-1, -2, -5, -6, 3, 2, -1, -2]

【讨论】:

    【解决方案3】:
        python 3.2
        a=[[4, 8], [5, 6, 9, 10], [13]] 
        [[x-y for x in a[i]for y in a[i+1]]for i in range(len(a)-1)]
    
        >>>[[-1, -2, -5, -6, 3, 2, -1, -2], [-8, -7, -4, -3]]
    
       another way:
        for i in range(len(a)-1):
              for v in a[i]:
                  y.append(list(v-h for h in a[i+1]))
    

    【讨论】:

      【解决方案4】:

      如果这是您要查找的内容,此代码将为您提供表格中每个元素与下一行中每个元素的差异:

      output = []
      for row_num in range(len(a)-1):
        row_output = []
        output.append(row_output)
        for elt_row in a[row_num]:
          elt_output = []
          row_output.append(elt_output)
          for elt_next_row in a[row_num + 1]:
            elt_output.append(elt_row - elt_next_row)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-14
        • 1970-01-01
        • 1970-01-01
        • 2013-09-25
        • 2020-03-04
        • 2013-05-24
        • 1970-01-01
        • 2021-11-27
        相关资源
        最近更新 更多