我將如何做到在Python以下幾點:Python的排列
first = ['John', 'David', 'Sarah']
last = ['Smith', 'Jones']
combined = ['John Smith', 'John Jones', 'David Smith', 'David Jones', 'Sarah Smith', 'Sarah Jones']
是否有所有排列組合的方法?
我將如何做到在Python以下幾點: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]
+1列表解析 – 2012-04-29 04:28:51
我不知道這方面的任何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
product
從itertools
將做的伎倆。
product(first, last)
會給返回發電機的first
和last
所有可能的組合。在那之後,你所需要做的就是連接第一個和最後一個名字。您可以在一個表達式做到這一點:
combined = [" ".join(pair) for pair in product(first, last)]
它也可以用字符串連接要做到這一點:
combined = [pair[0] + " " + pair[1] for pair in product(first, last)]
這種方法比較慢,雖然,作爲連接在翻譯完成的。總是建議使用"".join()
方法,因爲此代碼在C中執行。
您可以使用任何*語言自行編寫排列生成器。 – 2012-04-29 03:00:27