嵌套词典

2024-09-28 01:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一些类似FASTA的序列(不是FASTA,但是我定义了一些类似于从双鱼座服务器上剔除的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的答案

^{pr2}$

但我想要的是:

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

我不想因为下面的命令而需要所有额外的括号

^{3}$

(参见上面的代码片段)

有办法吗?在


Tags: 答案in服务器if定义not序列item
3条回答

可以将它们添加为元组:

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

这样,而不是:

^{pr2}$

问题是用逗号来“追加”一个元素,每次都会创建一个新的元组。要解决此问题,请使用列表和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)

更好的办法是,不要把potpasin变成一个普通的字典,而是用一个defaultdict来代替它。然后可以将代码简化为:

^{pr2}$

您的问题可以归结为展开嵌套列表并消除多余的条目:

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

因此,使用嵌套字典:

^{pr2}$

如果要消除重复条目:

^{3}$

希望这有帮助

相关问题 更多 >

    热门问题