Issue
I have multiple pairwise comparisons to do in order to find common items between the lists. My code below works. However, I would like to keep track of the names of the lists. which are geno1, geno2 and geno3. I'm not sure how to get the combinations refering to the variable names instead of the arrays. Although there are related questions on Stack overflow such as Getting method parameter names, I'm hoping to get a quite easy solution.Thank you in advance for your time.
import itertools #to get all pairwise combinations
geno1 = [1,2,3]
geno2 = [2,5]
geno3 = [1,2,4,5]
genotypes = [geno1,geno2,geno3]
combinations = list(itertools.combinations(genotypes,2))
for pair in combinations:
commonItem = [x for x in pair[0] if x in pair[1]]
print(f'{len(commonItem)} common items between {pair}')#Here instead of pair I want to know which pair of genotypes such as geno1 geno2, or geno1 geno3.
print(commonItem)
print()
Solution
Create a dictionary, where the keys are the name of the list and values are the lists that you originally have. You could do something using locals()
if you didn't want to write out the name of the lists as strings, but it's pretty hacky and I wouldn't recommend it:
import itertools
geno1 = [1,2,3]
geno2 = [2,5]
geno3 = [1,2,4,5]
genotypes = {"geno1": geno1, "geno2": geno2, "geno3": geno3}
combinations = list(itertools.combinations(genotypes.items(),2))
for (fst_name, fst_lst), (snd_name, snd_lst) in combinations:
commonItem = [x for x in fst_lst if x in snd_lst]
print(f'{len(commonItem)} common items between {fst_name} and {snd_name}')
print(commonItem)
print()
Output:
1 common items between geno1 and geno2
[2]
2 common items between geno1 and geno3
[1, 2]
2 common items between geno2 and geno3
[2, 5]
Answered By - BrokenBenchmark Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.