Reputation: 595
I am currently trying to create specific pairs from two python lists:
Input:
l1 = ["fc1", "fc2"]
l2 = ["fh1", "fh2"]
Expected output:
outl1 = [["fc1","fh1"],["fc2","fh2"]]
outl2 = [["fc2","fh1"],["fc1","fh2"]]
You'll have guessed from this example that a "fc*" must be matched with a "fh*" and that any occurance of the list cannot be repeated in the final output.
I must admit I am quite confused by all the documentation if found online about zip, enumerate, itertools etc...
Thanks a lot in advance for your help.
Upvotes: 0
Views: 129
Reputation: 3675
If I understand you correct, you want to create all possible lists of pairs ('fci', 'fhj'), such that in each list all the 'fci' appear only once and the same for 'fhj'.
You can use itertools.permuations
to achieve this. I generalized your example to include 3 elements per list.
from itertools import permutations
A = ["fc1", "fc2", "fc3"]
B = ["fh1", "fh2", "fh3"]
B_permuations = permutations(B)
for perm in B_permuations:
print([[a, b] for a, b in zip(A, perm)])
This will give you
[['fc1', 'fh1'], ['fc2', 'fh2'], ['fc3', 'fh3']]
[['fc1', 'fh1'], ['fc2', 'fh3'], ['fc3', 'fh2']]
[['fc1', 'fh2'], ['fc2', 'fh1'], ['fc3', 'fh3']]
[['fc1', 'fh2'], ['fc2', 'fh3'], ['fc3', 'fh1']]
[['fc1', 'fh3'], ['fc2', 'fh1'], ['fc3', 'fh2']]
[['fc1', 'fh3'], ['fc2', 'fh2'], ['fc3', 'fh1']]
Upvotes: 2
Reputation: 4973
if enumerate
, zip
and such is overwhelming at first use a simple for
loops
l1 = ["fc1", "fc2"]
l2 = ["fh1", "fh2"]
a = []
for i1 in l1:
a.append([[i1,i2] for i2 in l2])
for i in a:
print(i)
output
[['fc1', 'fh1'], ['fc1', 'fh2']]
[['fc2', 'fh1'], ['fc2', 'fh2']]
Upvotes: 0
Reputation: 48367
You can use zip
method by passing the both given lists as arguments.
For achieving the outl2
list you should use zip
method which accepts two arguments
: the l1
list, but reversed and l2
list.
zip
method makes an iterator that aggregates elements from each of the iterables.
With the other words, zip returns an iterator
of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
l1 = ["fc1", "fc2"]
l2 = ["fh1", "fh2"]
print([[a,b] for a,b in zip(l1,l2)])
print([[a,b] for a,b in zip(reversed(l1),l2)])
Output
[['fc1', 'fh1'], ['fc2', 'fh2']]
[['fc2', 'fh1'], ['fc1', 'fh2']]
Upvotes: 2