将来自不同列表的两个元素组合成一个坐标元组

时间:2012-09-07 00:14:24

标签: python list

所以我将这些元组放在另一个元组的两个列表中,看起来像

data_tuple = ([(1,2,3),(4,5,6)(7,8,9)],[(a,b,c),(d,e,f)(g,h,i)])

我想使用每个列表中相应的索引元素构建一组坐标,使其看起来像

final = [(2,b),(5,e),(8,h)]

这是我得到的:

for a in data_tuple[0]:
    x = a[1]
    for b in data_tuple[1]:
        y = b[1]
        print(x,y)

现在我只想检查我的迭代/缩进是否正确所以我还不需要将它们放入列表中。现在这个特定代码的结果是

(2,b)
(2,e)
(2,h)
(5,b)
(5,e)

依此类推,直到达到(8,h)。

如果我把打印线放到左边,在第二个for循环下,我得到

(2,h)
(5,h)
(8,h)

我该如何解决这个问题?对不起,如果我没有任何意义= /。你可以告诉我,我对Python非常陌生,所以我不熟悉很多导入模块。有什么帮助吗?

3 个答案:

答案 0 :(得分:2)

>>> print [(i[0][1],i[1][1]) for i in zip(*data_tuple)]
[(2, 'b'), (5, 'e'), (8, 'h')]

但通常清晰度比简洁更重要

我真的不明白你原来的问题,因为它看起来像预期的那样工作意味着你的缩进和迭代很好..

[edit]这就是你想要的东西

for i in range(len(data_tuple[0]):
    x,y = data_tuple[0][i][1],data_tuple[1][i][1],
    print (x,y)

>>> for numbr,letr in zip(*data_tuple):
...     x,y = numbr[1],letr[1]
...     print(x,y)
...

答案 1 :(得分:0)

这样的东西?

>>> data_tuple = ([(1,2,3),(4,5,6),(7,8,9)],[("a","b","c"),("d","e","f"),("g","h","i")])
>>> full_numbers_list, full_letters_list = data_tuple
>>> desired_output_idx = (1,)
>>>
>>> results = []
>>> for numbers, letters in zip(full_numbers_list, full_letters_list):
...     assert len(numbers) == len(letters) # make sure assumption is met
...     for i in range(len(numbers)): 
...         if i in desired_output_idx:
...             results.append((numbers[i], letters[i]))
...
>>> results
[(2, 'b'), (5, 'e'), (8, 'h')]

代替使用解压缩data_tuple的步骤,您可以使用*data_tuple解压缩您的元组以输入zip()函数。

>>> zip(*data_tuple)
[((1, 2, 3), ('a', 'b', 'c')), ((4, 5, 6), ('d', 'e', 'f')), ((7, 8, 9), ('g', 'h', 'i'))]
>>>
>>> # *data_tuple is the same as:
>>> numbers, letters = data_tuple
>>> zip(numbers, letters)
[((1, 2, 3), ('a', 'b', 'c')), ((4, 5, 6), ('d', 'e', 'f')), ((7, 8, 9), ('g', 'h', 'i'))]

答案 2 :(得分:0)

假设你总是想要第二个元素:

[ (a, b) for ((_,a,_), (_,b,_)) in zip(*data_tuple) ]

请注意,这会产生您指定的结果,但与您的算法不同,后者会产生笛卡尔积。这样就可以实现:

[ (a, b)
  for (_,a,_) in data_tuple[0]
  for (_,b,_) in data_tuple[1] ]

假设你总是想要第二个元素:

[ (a, b) for ((_,a,_), (_,b,_)) in zip(*data_tuple) ]

请注意,这会产生您指定的结果,但与您的算法不同,后者会产生笛卡尔积。这样就可以实现:

[ (a, b)
  for (_,a,_) in data_tuple[0]
  for (_,b,_) in data_tuple[1] ]

编辑:在回复您的评论时,这是我运行的会话:

>>> [ (a, b)
...   for (_,a,_) in data_tuple[0]
...   for (_,b,_) in data_tuple[1] ]
[(2, 'b'), (2, 'e'), (2, 'h'), (5, 'b'), (5, 'e'), (5, 'h'), (8, 'b'), (8, 'e'), (8, 'h')]

这是笛卡尔产品,根据您的原始代码。

然而,根据您修正的问题,我很确定您只想要我提供的第一个代码:

>>> [ (a, b) for ((_,a,_), (_,b,_)) in zip(*data_tuple) ]
[(2, 'b'), (5, 'e'), (8, 'h')]
相关问题