0

假设我有如下列表:

foo = [256, 456, 24, 79, 14]
bar = ['a', 'aa', 'dd', 'e', 'b']
baz = [2.9, 2.7, 1.9, 2.2, 1.1] 

我想要成对的 foo (我知道我可以使用iterools.combinations),但是我如何拥有它,以便当我在 中获取元素对时,在andfoo中获取相应的对?barbaz

例如,当我配对256and 456in 时foo,我以相同的顺序配对'a'and 'aa'in ,并且以相同的顺序配对in ?bar2.92.7baz

另外,当我采用组合时,我不应该担心(256, 456)两者(456, 256)都会被输出,因为如果我们插入一个按上述顺序排列的列表,我们实际上应该得到组合而不是更多的排列?

4

3 回答 3

1

这是一个用于对任意数量列表中的组合进行分组的通用函数:

>>> def grouped_combos(n, *ls):
...     for comb in itertools.combinations(zip(*ls), n):
...         yield comb
>>> list(grouped_combos(2, [256, 456, 24, 79, 14], ['a', 'aa', 'dd', 'e', 'b']))
[((256, 'a'), (456, 'aa')), 
 ((256, 'a'), (24, 'dd')), 
 ((256, 'a'), (79, 'e')), 
 ((256, 'a'), (14, 'b')), 
 ((456, 'aa'), (24, 'dd')), 
 ((456, 'aa'), (79, 'e')), 
 ((456, 'aa'), (14, 'b')), 
 ((24, 'dd'), (79, 'e')), 
 ((24, 'dd'), (14, 'b')), 
 ((79, 'e'), (14, 'b'))]
>>> list(grouped_combos(4, [1, 2, 3, 4, 5], "abcde", "xyzzy"))
[((1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z'), (4, 'd', 'z')), 
 ((1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z'), (5, 'e', 'y')), 
 ((1, 'a', 'x'), (2, 'b', 'y'), (4, 'd', 'z'), (5, 'e', 'y')), 
 ((1, 'a', 'x'), (3, 'c', 'z'), (4, 'd', 'z'), (5, 'e', 'y')), 
 ((2, 'b', 'y'), (3, 'c', 'z'), (4, 'd', 'z'), (5, 'e', 'y'))]
于 2013-11-02T16:46:16.873 回答
1

您可以组合索引,然后使用这些索引组合来访问各个项目:

indexes = list(range(len(foo)))
for i, j in itertools.combinations(indexes, 2):
     print(foo[i], foo[j])
     print(bar[i], bar[j])
     print(baz[i], baz[j])
于 2013-11-02T16:44:56.517 回答
1
for c in itertools.combinations(zip(foo, bar, baz), 2):
    for u in zip(*c):
        print(u)

输出:

(256, 456)
('a', 'aa')
(2.9, 2.7)
(256, 24)
('a', 'dd')
(2.9, 1.9)
(256, 79)
('a', 'e')
(2.9, 2.2)
(256, 14)
('a', 'b')
(2.9, 1.1)
(456, 24)
('aa', 'dd')
(2.7, 1.9)
(456, 79)
('aa', 'e')
(2.7, 2.2)
(456, 14)
('aa', 'b')
(2.7, 1.1)
(24, 79)
('dd', 'e')
(1.9, 2.2)
(24, 14)
('dd', 'b')
(1.9, 1.1)
(79, 14)
('e', 'b')
(2.2, 1.1)
于 2013-11-02T16:44:58.477 回答