简体   繁体   中英

List comprehensions in python

Is there any way I can combine two list a and b into c using list comprehensions in python,

a=[1,2,3]
b=['a','b']

c=['1a','1b','2a','2b','3a','3b'] 
>>> from itertools import product
>>> a=[1,2,3]
>>> b=['a','b']
>>> ['%d%s' % el for el in product(a,b)]
['1a', '1b', '2a', '2b', '3a', '3b']

With new string formatting

>>> ['{0}{1}'.format(*el) for el in product(a,b)]
['1a', '1b', '2a', '2b', '3a', '3b']
>>> a = [1,2,3]
>>> b = ['a', 'b']
>>> c = ['%d%c' % (x, y) for x in a for y in b]
>>> c
['1a', '1b', '2a', '2b', '3a', '3b']

c = ["%d%s" % (x,y) for x in a for y in b]使用c = ["%d%s" % (x,y) for x in a for y in b]

List comprehensions can loop over multiple objects.

In[3]: [str(a1)+b1 for a1 in a for b1 in b]

Out[3]: ['1a', '1b', '2a', '2b', '3a', '3b']

Note the slight subtlety of converting the number into a string.

只需使用“嵌套”版本。

c = [str(i) + j for i in a for j in b]
import itertools
c=[str(r)+s for r,s in itertools.product(a,b)]

somewhat similar version of jamylak's solution:

>>> import itertools
>>> a=[1,2,3]
>>> b=['a','b']
>>>[str(x[0])+x[1] for x in itertools.product(a,b)]
['1a', '1b', '2a', '2b', '3a', '3b']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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