如何获取成对组合的变量名?

How to get the variable names of pairwise combinations?

我要进行多次成对比较,以便找到列表之间的共同项。我下面的代码有效。但是,我想跟踪列表的名称。它们是 geno1、geno2 和 geno3。我不确定如何获取引用变量名而不是数组的组合。虽然 Stack overflow 上有相关问题,例如 ,但我希望能提前为您解答 solution.Thank。

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()

创建一个字典,其中键是列表的名称,值是您最初拥有的列表。如果您不想将列表的名称写成字符串,您可以使用 locals() 来做一些事情,但它很老套,我不推荐它:

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()

输出:

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]

如果您想将名称视为数据,则应将它们存储为数据。 dict 可以让您将名称和值放在一起:

import itertools

genotypes = {
    'geno1': [1,2,3],
    'geno2': [2,5],
    'geno3': [1,2,4,5],
    }

combinations = itertools.combinations(genotypes.items(), 2)
for (k1, v1), (k2, v2) in combinations:
    commonItem = [x for x in v1 if x in v2]
    print(f'{len(commonItem)} common items between {k1} and {k2}')
    print(commonItem)

输出:

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]

有关更多上下文,请参阅:

  • How do I create variable variables?
  • Getting the name of a variable as a string

您最好将其全部放入字典中。然后就可以先得到名字的组合,只看循环里面的实际列表:

import itertools

genotypes = {
    'geno1': [1,2,3],
    'geno2': [2,5],
    'geno3': [1,2,4,5],
}
combinations = list(itertools.combinations(genotypes,2))


for left_name, right_name in combinations:
    left_geno = genotypes[left_name]
    right_geno = genotypes[right_name]
    commonItem = [x for x in left_geno if x in right_geno]
    print(f'{len(commonItem)} common items between {left_name} and {right_name}: {commonItem}\n')