我有一张这样的名单。
a = [1, 2, 3, 4]
b = [3, 2, 0.3]
c = [0.1, 3, 6.8]
d = [9, 2.5, 7, 2]
x = [a, b, c, d]我想把它们像这样配对:
[a, b], [b, a], [a, c], [c, a], [a, d], [d, a], [b, c], [c, b], [b, d], [d, b], [c, d], [d, c]我就是这样做的:
for i in range(len(x)):
for j in range(len(x):
if i!= j:
#TODO...
print(x[i], x[j])我的问题是:是否有更明智的方法来提高性能?(当x有6-7项时,我可以告诉你,它的速度慢了很多。)
你的任何意见都会对我有很大帮助。
谢谢
发布于 2017-09-11 07:31:07
This comment给了我一个有趣的想法。在这里,使用itertools.combinations,它按照您要查找的顺序返回项。
from itertools import combinations
def foo(x):
for x in combinations(x, 2):
yield from (x, x[::-1]) # python3.3+
for i in foo(['a', 'b', 'c', 'd']):
print(i)
('a', 'b')
('b', 'a')
('a', 'c')
('c', 'a')
('a', 'd')
('d', 'a')
('b', 'c')
('c', 'b')
('b', 'd')
('d', 'b')
('c', 'd')
('d', 'c')将['a', 'b', 'c', 'd']替换为[a, b, c, d],这是列表的实际列表。
注意:对于python <3.3,您需要yield x; yield x[::-1],因为不支持yield from。
发布于 2017-09-11 07:22:38
a = [1, 2, 3, 4]
b = [3, 2, 0.3]
c = [0.1, 3, 6.8]
d = [9, 2.5, 7, 2]
x = [a, b, c, d]
import itertools
list(itertools.permutations(x, 2))
[([1, 2, 3, 4], [3, 2, 0.3]), ([1, 2, 3, 4], [0.1, 3, 6.8]), ([1, 2, 3, 4], [9, 2.5, 7, 2]), ([3, 2, 0.3], [1, 2, 3, 4]), ([3, 2, 0.3], [0.1, 3, 6.8]), ([3, 2, 0.3], [9, 2.5, 7, 2]), ([0.1, 3, 6.8], [1, 2, 3, 4]), ([0.1, 3, 6.8], [3, 2, 0.3]), ([0.1, 3, 6.8], [9, 2.5, 7, 2]), ([9, 2.5, 7, 2], [1, 2, 3, 4]), ([9, 2.5, 7, 2], [3, 2, 0.3]), ([9, 2.5, 7, 2], [0.1, 3, 6.8])]如注释所示,对于特定的顺序,可以使用itertools.combinations
list(itertools.chain.from_iterable(map(lambda x: (x, x[::-1]),
itertools.combinations(x, 2))))
[([1, 2, 3, 4], [3, 2, 0.3]), ([3, 2, 0.3], [1, 2, 3, 4]), ([1, 2, 3, 4], [0.1, 3, 6.8]), ([0.1, 3, 6.8], [1, 2, 3, 4]), ([1, 2, 3, 4], [9, 2.5, 7, 2]), ([9, 2.5, 7, 2], [1, 2, 3, 4]), ([3, 2, 0.3], [0.1, 3, 6.8]), ([0.1, 3, 6.8], [3, 2, 0.3]), ([3, 2, 0.3], [9, 2.5, 7, 2]), ([9, 2.5, 7, 2], [3, 2, 0.3]), ([0.1, 3, 6.8], [9, 2.5, 7, 2]), ([9, 2.5, 7, 2], [0.1, 3, 6.8])]发布于 2017-09-11 07:35:31
你可以试试zip
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
x = [a,b,c]
y = []
for i in range (0,len(x)):
for j in range (i + 1, len(x)):
y.append(zip(x[i],x[j]))
y.append(zip(x[j],x[i]))
print yhttps://stackoverflow.com/questions/46150179
复制相似问题