Pythonでリスト内包表記を使用して2つのリストaとbをcに結合する方法はありますか?
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']
新しい文字列フォーマット
>>> ['{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]
リスト内包表記は、複数のオブジェクトをループする可能性があります。
In[3]: [str(a1)+b1 for a1 in a for b1 in b]
Out[3]: ['1a', '1b', '2a', '2b', '3a', '3b']
数値を文字列に変換する際の微妙な点に注意してください。
「ネストされた」バージョンを使用するだけです。
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)]
jamylakのソリューションのやや類似したバージョン:
>>> 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']