gpt4 book ai didi

python - 配对嵌套列表中的元素

转载 作者:行者123 更新时间:2023-11-28 20:15:37 25 4
gpt4 key购买 nike

我有一个这样的列表列表。

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 个项目时,我可以看出它变慢了很多)。

您的任何意见都会对我有很大帮助。

谢谢

最佳答案

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

关于python - 配对嵌套列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46150179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com