How can I combine these two into one list comprehension? Thank you.
transactions = [[2, 8, 3, 6, 1, 9], [0, 5, 9], [0, 9], [4, 7, 0, 5, 9],
[8, 3], [1, 6, 3, 8], [9, 0, 5], [3, 8], [5, 7, 0, 4], [3, 1, 2, 6, 0]]
code1
new_transaction= []
for num in transactions:
num = sorted(num)
new_transaction.append(num)
new_transaction
code2
product_pairs = [[(num[i],num[j]) for i in range(len(num)) for j in range(i 1, len(num))]for num in new_transaction]
print(product_pairs)
expected output:
[[(1, 2), (1, 3), (1, 6), (1, 8), (1, 9), (2, 3), (2, 6), (2, 8), (2, 9), (3, 6), (3, 8), (3, 9), (6, 8), (6, 9), (8, 9)], [(0, 5), (0, 9), (5, 9)], [(0, 9)], [(0, 4), (0, 5), (0, 7), (0, 9), (4, 5), (4, 7), (4, 9), (5, 7), (5, 9), (7, 9)], [(3, 8)], [(1, 3), (1, 6), (1, 8), (3, 6), (3, 8), (6, 8)], [(0, 5), (0, 9), (5, 9)], [(3, 8)], [(0, 4), (0, 5), (0, 7), (4, 5), (4, 7), (5, 7)], [(0, 1), (0, 2), (0, 3), (0, 6), (1, 2), (1, 3), (1, 6), (2, 3), (2, 6), (3, 6)]]
CodePudding user response:
You can combine these two like this.
transactions = [[2, 8, 3, 6, 1, 9], [0, 5, 9], [0, 9], [4, 7, 0, 5, 9], [8, 3], [1, 6, 3, 8], [9, 0, 5], [3, 8], [5, 7, 0, 4], [3, 1, 2, 6, 0]]
product_pairs = [[(num[i],num[j]) for i in range(len(num)) for j in range(i 1, len(num))]for num in [sorted(num) for num in transactions]]
print(product_pairs)
This code returns the same output.
from itertools import combinations
transactions = [[2, 8, 3, 6, 1, 9], [0, 5, 9], [0, 9], [4, 7, 0, 5, 9], [8, 3], [1, 6, 3, 8], [9, 0, 5], [3, 8], [5, 7, 0, 4], [3, 1, 2, 6, 0]]
[a.sort() for a in transactions]
product_pairs = [list(combinations(a,2)) for a in transactions]
print(product_pairs)