Pythonで次のことをどのように達成しますか:
first = ['John', 'David', 'Sarah']
last = ['Smith', 'Jones']
combined = ['John Smith', 'John Jones', 'David Smith', 'David Jones', 'Sarah Smith', 'Sarah Jones']
すべての順列を組み合わせる方法はありますか?
Pythonで次のことをどのように達成しますか:
first = ['John', 'David', 'Sarah']
last = ['Smith', 'Jones']
combined = ['John Smith', 'John Jones', 'David Smith', 'David Jones', 'Sarah Smith', 'Sarah Jones']
すべての順列を組み合わせる方法はありますか?
import itertools
combined = [f + ' ' + l for f, l in itertools.product(first, last)]
もっとエレガントな解決策があるかどうかはわかりませんが、これはうまくいくはずです:
[x + " " + y for x in first for y in last]
product
からitertools
トリックを行います。
product(first, last)
は、 と のすべての可能な組み合わせを含むジェネレータを返しfirst
ますlast
。その後、姓と名を連結するだけです。これを 1 つの式で行うことができます。
combined = [" ".join(pair) for pair in product(first, last)]
文字列連結でこれを行うことも可能です:
combined = [pair[0] + " " + pair[1] for pair in product(first, last)]
ただし、インタープリターで連結が行われるため、この方法は遅くなります。"".join()
このコードは C で実行されるため、常にこのメソッドを使用することをお勧めします。
私はこれのための python ユーティリティ メソッドを認識していませんが、以下は同じことを達成します:
def permutations(first, second):
result = []
for i in range(len(first)):
for j in range(len(second)):
result.append(first[i] + ' ' + second[j])
return result