英文:
Given two lists, how to create a unique combinations and the elements in each combination are different? Python
问题
以下是已翻译的内容:
输入:
list1 = ['Town1','Town2','Town3','Town4','Town5']
list2 = ['Town1','Town2','Town3','Town4','Town5']
输出:
[('Town1', 'Town2'), ('Town3', 'Town4'), ('Town4', 'Town4'), ('Town4', 'Town5'), ('Town1', 'Town4'), ('Town3', 'Town5'), ('Town1', 'Town3'), ('Town2', 'Town4'), ('Town1', 'Town5'), ('Town2', 'Town3'), ('Town2', 'Town5')]
我尝试了:
comb = list(product(list1, list2))
comb1 = [sorted(item) for item in comb]
comb2 = list(set(map(tuple, comb1)))
但结果中包括了('Town1', 'Town1')。
英文:
Inputs:
list1 = ['Town1','Town2','Town3','Town4','Town5']
list2 = ['Town1','Town2','Town3','Town4','Town5']
Outputs:
[('Town1', 'Town2'), ('Town3', 'Town4'), ('Town4', 'Town4'), ('Town4', 'Town5'), ('Town1', 'Town4'), ('Town3', 'Town5'), ('Town1', 'Town3'), ('Town2', 'Town4'), ('Town1', 'Town5'), ('Town2', 'Town3'), ('Town2', 'Town5')]
I tried :
comb = list(product(list1,list2))
comb1 = [sorted(item) for item in comb]
comb2 = list(set(map(tuple,comb1)))
But ('Town1', 'Town1')
is involved in the result.
答案1
得分: 1
你可以使用一个列表推导式来排除具有重复元素的配对:
from itertools import product
list1 = ['Town1', 'Town2', 'Town3', 'Town4', 'Town5']
list2 = ['Town1', 'Town2', 'Town3', 'Town4', 'Town5']
comb = [pair for pair in product(list1, list2) if pair[0] != pair[1]]
print(comb)
输出结果是:
[('Town1', 'Town2'), ('Town1', 'Town3'), ('Town1', 'Town4'), ('Town1', 'Town5'), ('Town2', 'Town1'), ('Town2', 'Town3'), ('Town2', 'Town4'), ('Town2', 'Town5'), ('Town3', 'Town1'), ('Town3', 'Town2'), ('Town3', 'Town4'), ('Town3', 'Town5'), ('Town4', 'Town1'), ('Town4', 'Town2'), ('Town4', 'Town3'), ('Town4', 'Town5'), ('Town5', 'Town1'), ('Town5', 'Town2'), ('Town5', 'Town3'), ('Town5', 'Town4')]
英文:
You can exclude the pairs with repeated elements with a list comprehension:
from itertools import product
list1 = ['Town1','Town2','Town3','Town4','Town5']
list2 = ['Town1','Town2','Town3','Town4','Town5']
comb = [pair for pair in product(list1,list2) if pair[0] != pair[1]]
print(comb)
The output is:
[('Town1', 'Town2'), ('Town1', 'Town3'), ('Town1', 'Town4'), ('Town1', 'Town5'), ('Town2', 'Town1'), ('Town2', 'Town3'), ('Town2', 'Town4'), ('Town2', 'Town5'), ('Town3', 'Town1'), ('Town3', 'Town2'), ('Town3', 'Town4'), ('Town3', 'Town5'), ('Town4', 'Town1'), ('Town4', 'Town2'), ('Town4', 'Town3'), ('Town4', 'Town5'), ('Town5', 'Town1'), ('Town5', 'Town2'), ('Town5', 'Town3'), ('Town5', 'Town4')]
答案2
得分: 0
list1 = ['Town1', 'Town2', 'Town3', 'Town4', 'Town5']
list2 = ['Town1', 'Town2', 'Town3', 'Town4', 'Town5']
result = []
for i in list1:
for j in list2:
if i != j:
result.append((i, j))
print(result)
英文:
list1 = ['Town1','Town2','Town3','Town4','Town5']
list2 = ['Town1','Town2','Town3','Town4','Town5']
result = []
for i in list1:
for j in list2:
if i != j:
result.append((i, j))
print(result)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论