Domanda

first=[1,2,3,4,5]
second=['a','b','c','d','e']
final=['1a','2a','3a','1b','2b',3b','1c','2c','3c']

I want to combine two lists in python but I don't care about order. Aka I don't want '1a' and 'a1'.

È stato utile?

Soluzione 2

A simple list comprehension will work.

print([str(first[i])+second[i] for i in range(len(first))])

Altri suggerimenti

>>> import itertools
>>> first=[1,2,3,4,5]
>>> second=['a','b','c','d','e']
>>> final = [''.join(str(i) for i in s) for s in itertools.product(first, second)]
>>> final
['1a', '1b', '1c', '1d', '1e', '2a', '2b', '2c', '2d', '2e', '3a', '3b', '3c', '3d', '3e', '4a', '4b', '4c', '4d', '4e', '5a', '5b', '5c', '5d', '5e']
final = list()
for i in first:
    for j in second:
        final.append(str(i)+j)

If you've only got two sequences to "multiply" like this, and your iteration is dead-simple, a nested loop in a comprehension is perfectly readable:

['{}{}'.format(a, b) for a in first for b in second]

If you have a longer, or dynamic, list, you want itertools.product, as in inspectorG4dget's answer.

If you have anything more complicated than just iterating over the product, you probably want explicit loop statements rather than a comprehension (or maybe factor part of it out into a generator function and use that with the nested comp or product call).

One way without using itertools, map or zip is:

first = [1, 2, 3, 4, 5]
second = ['a', 'b', 'c', 'd', 'e']

print [str(i) + j for i in first for j in second]

Output:

['1a', '1b', '1c', '1d', '1e', '2a', '2b', '2c', '2d', '2e', '3a', '3b', '3c', '3d', '3e', '4a', '4b', '4c', '4d', '4e', '5a', '5b', '5c', '5d', '5e']
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top