為了找到串列之間的共同專案,我需要進行多次成對比較。我下面的代碼有效。但是,我想跟蹤串列的名稱。分別是geno1、geno2和geno3。我不確定如何獲取參考變數名而不是陣列的組合。雖然有關于堆疊溢位的相關問題,例如獲取方法引數名稱,但我希望得到一個非常簡單的解決方案。提前感謝您的時間。
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()
uj5u.com熱心網友回復:
創建一個字典,其中鍵是串列的名稱,值是您最初擁有的串列。locals()如果您不想將串列的名稱寫成字串,您可以使用它來做一些事情,但它非常hacky,我不推薦它:
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]
uj5u.com熱心網友回復:
你可能最好把它都放進字典里。然后您可以先獲取名稱的組合,然后僅在回圈內查看實際串列:
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')
uj5u.com熱心網友回復:
如果要將名稱視為資料,則應將它們存盤為資料。Adict將讓您將名稱和值保存在一起:
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]
有關更多背景關系,請參閱:
- 如何創建變數變數?
- 獲取變數名作為字串
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478360.html
上一篇:Python系結變數
