在数组中的子数组中使用元组的条件

时间:2014-03-17 17:31:58

标签: python tuples conditional-statements arrays

A = [[(1,2,0),(3,4,0),(5,6,0)],[(7,8,1),(9,10,1),(11,12,1)],[(13,14,0),(15,16,0),(17,18,0)]]

我在尝试从给定子数组中的每个元组中求和第三个元素然后对其应用某些条件时遇到问题。即,希望上述输出为:

B = ['X',(7,8,9,19,11,12),'X']

这是我目前正在做的事情。请注意,元组的数量会有所不同,但每个元素的数量都是不变的。

i = 0
while i < len(A):
    if sum([X[2] for X in A[i]]) == 0:
        B.append('X')
    else:
        arr = [x[0:2] for x in A[i]]
        B.append(list(itertools.chain.from_iterable(arr)))
    i = i+1 

我使用多个语句后遇到的具体问题已经解决,其形式如下:

A = [[(1,2,0),(3,4,0),(4,5,0)],[(6,7,1),(8,9,1)],[(10,11,0)]]
B = ['X' if not sum(t[2] for t in sub) and len(sub) >= 2 else tuple(itertools.chain.from_iterable(t[:2] for t in sub)) for sub in A]
print B

['X', (6, 7, 8, 9), (10, 11)]

2 个答案:

答案 0 :(得分:2)

您可以使用列表理解:

['X' if not sum(t[2] for t in sub) else tuple(i for t in sub for i in t[:2])
 for sub in A]

演示:

>>> A = [[(1,2,0),(3,4,0),(5,6,0)],[(7,8,1),(9,10,1),(11,12,1)],[(13,14,0),(15,16,0),(17,18,0)]]
>>> ['X' if not sum(t[2] for t in sub) else tuple(i for t in sub for i in t[:2])
...  for sub in A]
['X', (7, 8, 9, 10, 11, 12), 'X']

或者,如果你真的还想使用itertools.chain()

from itertools import chain

['X' if not sum(t[2] for t in sub) else tuple(chain.from_iterable(t[:2] for t in sub))
 for sub in A]

再次,作为演示:

>>> from itertools import chain
>>> ['X' if not sum(t[2] for t in sub) else tuple(chain.from_iterable(t[:2] for t in sub))
...  for sub in A]
['X', (7, 8, 9, 10, 11, 12), 'X']

答案 1 :(得分:1)

如果您只想在每个子列表中使用前两个元组作为输出,则需要明确说明:

arr = [x[0:2] for x in A[i][:2]]

编辑由于某些原因您显然现在只想要前两个。其余的仍然存在:


更一般地说,列表理解在这里更简洁:

 B = [tuple(itertools.chain.from_iterable(t[:2] for t in l)) 
      if sum(t[2] for t in l) else 'X' for l in A]

这给了我你想说的结果:

>>> B
['X', (7, 8, 9, 10, 11, 12), 'X']