gpt4 book ai didi

python - 列表值之间的组合

转载 作者:行者123 更新时间:2023-11-30 22:57:19 25 4
gpt4 key购买 nike

假设我有以下列表:

letters = ['a','b','c']
numbers = ['one','two']
others = ['here','there']

我想要所有值的所有可能的组合。我正在执行以下操作:

from itertools import permutations
b = []
b.extend(letters)
b.extend(numbers)
b.extend(others)
result1 = list(permutations(b,2))

结果还可以。但我更具体地想要知道组合的“类型”。例如结果应该是:

('a','b','letters-letters')

('a','one','letters-numbers')
('one','a','letters-numbers')

我正在使用以下代码:

from itertools import product
result2=[]
result2.extend([x+('letter-letter',) for x in list(permutations(letters ,2))])
result2.extend([x+('number-number',) for x in list(permutations(numbers,2))])
result2.extend([x+('other-other',) for x in list(permutations(others,2))])
result2.extend([x+('number-letter',) for x in list(product(numbers,letters))])
result2.extend([x+('number-letter',) for x in list(product(letters,numbers))])
result2.extend([x+('number-others',) for x in list(product(numbers,others))])
result2.extend([x+('number-others',) for x in list(product(others,numbers))])
result2.extend([x+('letters-others',) for x in list(product(letters,others))])
result2.extend([x+('letters-others',) for x in list(product(others,letters))])

有没有更快速、更优雅的方法来做到这一点?

最佳答案

IIUC,关键是将元素所属的数据系列与元素耦合起来。例如:

from itertools import permutations

data = {'letters': ['a','b','c'],
'numbers': ['one','two'],
'others': ['here','there']}

poss = [(v,k) for k, vv in data.items() for v in vv]
results = (list(zip(*p)) for p in permutations(poss, 2))
results = [p[0] + ('-'.join(p[1]),) for p in results]

给我

[('a', 'b', 'letters-letters'),
('a', 'c', 'letters-letters'),
('a', 'here', 'letters-others'),
...
('two', 'here', 'numbers-others'),
('two', 'there', 'numbers-others'),
('two', 'one', 'numbers-numbers')]

这是有效的,因为我们从一个 poss 开始,看起来像

>>> poss[:3]
[('a', 'letters'), ('b', 'letters'), ('c', 'letters')]

然后从中选择两个元素,使用 zip-star 将每个选定的对变成类似的内容

>>> next(list(zip(*p)) for p in permutations(poss, 2))
[('a', 'b'), ('letters', 'letters')]

关于python - 列表值之间的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36721747/

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