簡體   English   中英

嵌套字典

[英]Nested dictionary

我正在研究一些類似於FASTA的序列(不是FASTA,但是我定義的東西與從PISCES服務器中剔除的PDB類似)。

我有個問題。 我沒有一個叫做nCatSeq的序列,其中有多個nBasinSeq 我瀏覽了一個大的PDB文件,我想為每個nCatSeq提取對應的nBasinSeq而在字典中沒有冗余。 下面給出了執行此操作的代碼段。

nCatSeq=item[1][n]+item[1][n+1]+item[1][n+2]+item[1][n+3]
nBasinSeq=item[2][n]+item[2][n+1]+item[2][n+2]+item[2][n+3]
if nCatSeq not in potBasin:
    potBasin[nCatSeq]=nBasinSeq
else:   
    if nBasinSeq not in potBasin[nCatSeq]:
        potBasin[nCatSeq]=potBasin[nCatSeq],nBasinSeq
    else:
        pass

我得到以下作為一個nCatSeq的答案,

'4241': ((('VUVV', 'DDRV'), 'DDVG'), 'VUVV')

但是我想要的是:

'4241':('VUVV','DDRV','DDVG','VUVV')

由於以下命令,我不需要所有多余的括號

potBasin[nCatSeq]=potBasin[nCatSeq],nBasinSeq 

(請參見上面的代碼段)

有沒有辦法做到這一點 ?

問題是用逗號“附加”一個元素,每次都會創建一個新的元組。 為了解決這個問題,您可以使用列表並append

nCatSeq=item[1][n]+item[1][n+1]+item[1][n+2]+item[1][n+3]
nBasinSeq=item[2][n]+item[2][n+1]+item[2][n+2]+item[2][n+3]
if nCatSeq not in potBasin:
    potBasin[nCatSeq]=[nBasinSeq]
elif nBasinSeq not in potBasin[nCatSeq]:
        potBasin[nCatSeq].append(nBasinSeq)

更好的是,而不是使potBasin成為普通字典,而將其替換為defaultdict 然后可以將代碼簡化為:

# init stuff
from collections import defaultdict
potBasin = defaultdict(list)

# inside loop
nCatSeq=item[1][n]+item[1][n+1]+item[1][n+2]+item[1][n+3]
nBasinSeq=item[2][n]+item[2][n+1]+item[2][n+2]+item[2][n+3]
potBasin[nCatSeq].append(nBasinSeq)

您可以將它們添加為元組:

if nCatSeq not in potBasin:
    potBasin[nCatSeq] = (nBasinSeq,)
else:
    if nBasinSeq not in potBasin[nCatSeq]:
        potBasin[nCatSeq] = potBasin[nCatSeq] + (nBasinSeq,)

這樣,而不是:

(('VUVV', 'DDRV'), 'DDVG')
# you will get
('VUVV', 'DDRV', 'DDVG') # == ('VUVV', 'DDRV')+ ('DDVG',)

您的問題歸結為拼合嵌套列表並消除冗余條目:

def flatten(nested, answer=None):
    if answer is None:
        answer = []
    if nested == []:
        return answer
    else:
        n = nested[0]
        if is instance(n, tuple):
            return flatten(nested[1:], nested(n[0], answer))
        else:
            return flatten(nested[1:], answer+n[0])

因此,使用您的嵌套字典:

for k in nested_dict:
    nested_dict[k] = tuple(flatten(nested_dict[k]))

如果要消除重復的條目:

for k in nested_dict:
    nested_dict[k] = tuple(set(flatten(nested_dict[k])))

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM