2

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

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 非常陌生,所以我不熟悉很多导入模块。请问有什么帮助吗?

4

3 回答 3

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

但通常清晰比简洁更重要

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

[编辑] 这就是我想的你想要的

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)
...
于 2012-09-07T00:18:41.460 回答
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')]
于 2012-09-07T00:39:29.773 回答
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'))]
于 2012-09-07T00:35:02.323 回答