List multiplication

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 to do L * L, but that didn't work. Can someone tell me how to get this in python.

+5
source share
7 answers

The module itertoolscontains a number of useful functions for this kind of thing. It looks like you can search 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)]
+13
source

You can do this with a list:

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

change

itertools.product, , 2.6. , Python 2.0. itertools.product, , , ( , ).

+22

itertools, product.

L =[1,2,3]

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

:

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

:

>>> 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')]
>>> 

Python 2.6 - Python, .

+3

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

, ,

0

, :

L2 = [(x, y) x L x L], L .

? , L * L python.

0

:

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

This one has an O (n ^ 2) runtime, and therefore it is rather slow, but you can consider it a “vintage” style code.

0
source

All Articles