开发者

List multiplication [duplicate]

This question already has answers here: 开发者_高级运维 Operation on every pair of element in a list (5 answers) Closed 6 months ago.

I have a list L = [a, b, c] and I want to generate a list of tuples :

[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...] 

I tried doing L * L but it didn't work. Can someone tell me how to get this in python.


You can do it with a list comprehension:

[ (x,y) for x in L for y in L]

edit

You can also use itertools.product as others have suggested, but only if you are using 2.6 onwards. The list comprehension will work will all versions of Python from 2.0. If you do use itertools.product bear in mind that it returns a generator instead of a list, so you may need to convert it (depending on what you want to do with it).


The itertools module contains a number of helpful functions for this sort of thing. It looks like you may be looking for product:

>>> import itertools
>>> L = [1,2,3]
>>> itertools.product(L,L)
<itertools.product object at 0x83788>
>>> list(_)
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]


Take a look at the itertools module, which provides a product member.

L =[1,2,3]

import itertools
res = list(itertools.product(L,L))
print(res)

Gives:

[(1,1),(1,2),(1,3),(2,1), ....  and so on]


Two main alternatives:

>>> L = ['a', 'b', 'c']
>>> import itertools
>>> list(itertools.product(L, L))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
>>> [(one, two) for one in L for two in L]
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
>>> 

the former one needs Python 2.6 or better -- the latter works in just about any Python version you might be tied to.


x = [a,b,c] y = [] for item in x: for item2 in x: y.append((item, item2))

Maybe not the Pythonic way but working


Ok I tried :

L2 = [(x,y) for x in L for x in L] and this got L square.

Is this the best pythonic way to do this? I would expect L * L to work in python.


The most old fashioned way to do it would be:

def perm(L):
    result = []
    for i in L:
        for j in L:
            result.append((i,j))
    return result

This has a runtime of O(n^2) and is therefore quite slow, but you could consider it to be "vintage" style code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜