简体   繁体   English

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

[英]how to collect many tuple from a list in python in one line?

for example: 例如:

If I want to make a array b from a like this: 如果我想从这样的数组b:

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

then b will be [1, 2, 3] 那么b将是[1, 2, 3]

now, I want to make a tuple list like this: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] from a 现在,我想制作一个这样的元组列表:[(1,2),(1,3),(2,1),(2,3),(3,1),(3,2)]一种

how to write this in one line? 如何写成一行?

I know how to write this function like this: 我知道如何写这样的功能:

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

but I wonder how to write this function in one line? 但我想知道如何在一行中编写此函数?

Simply use itertools.permutations : 只需使用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)]
>>>a = [1, 2, 3]
>>>b = [(n,m) for n in a for m in a if n!=m]
>>>
>>>print b
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM