gpt4 book ai didi

python - 如何在一行中从 python 列表中收集许多元组?

转载 作者:太空宇宙 更新时间:2023-11-04 09:03:39 25 4
gpt4 key购买 nike

例如:

如果我想从 a 中创建一个数组 b:

a = [1, 2, 3]
b = [i for i in a]

那么 b 将是 [1, 2, 3]

现在,我想制作一个这样的元组列表:[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] 来自

如何在一行中写这个?

我知道怎么写这个函数:

b = []
for i in a:
for j in a:
if i == j: continue
b.append((i, j))

但我想知道如何在一行中编写这个函数?

最佳答案

只需使用 itertools.permutations :

>>> from itertools import permutations
>>> a = [1, 2, 3]
>>> list(permutations(a, 2))
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

关于python - 如何在一行中从 python 列表中收集许多元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23027731/

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