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.
CodePudding user response:
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')]
CodePudding user response:
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)