【问题标题】:List not appending in the correct order列表未按正确顺序附加
【发布时间】:2021-08-08 16:01:44
【问题描述】:

在这段代码中,我试图将基因 ID 的基因描述附加到前 50 个 R 值。我得到了两个列表 top50 和 geneanno。

列表 top50 看起来像 [0.5218951111466706, 'AHY40589'] 列表geneanno 看起来像['AHY39293', 'Disulfide bond formation protein DsbB\n']

下面的代码显示了我如何附加列表,但我似乎无法附加与基因 ID 对应的正确基因描述。

    r_sorted = sorted(r_value)
unsorted = []
for s in r_sorted:
  if s not in unsorted:
    unsorted.append(s)
top50 = unsorted[::-1][:50]                           #top 50 with highest correlation
print(top50)

annotation = []
path = '/content/drive/abc_gene_anno.txt'
with open(path,'r') as f:
  geneanno = [l.split('\t') for l in f] #obtain gene ids
  for d in geneanno:
    for c in top50:
      if c[1] in d[0]:
        annotation.append(d[1][:-1])
print(d)
print(c)
print(annotation)

输出是

[[0.9999999999999999, 'AHY39286'], [0.939173984187146, 'AHY39284']]
['AHY39293', 'Disulfide bond formation protein DsbB\n']
[0.5218951111466706, 'AHY40589']
['Cysteine-rich domain', 'Cysteine-rich domain', 'FdhD/NarQ family', 'Protein of unknown function (DUF979)']

例如使用 r 值最高的 Gene ID (AHY39286),

但是,我的代码打印了这个

【问题讨论】:

  • 想要的输出是什么?
  • @BenWo 注释['Pyridine nucleotide-disulphide oxidoreductase', 'Dihydroprymidine dehydrogenase domain II, 4Fe-4S cluster'](基因描述)所需的输出,它对应于geneanno [['AHY39286', 'Pyridine nucleotide-disulphide oxidoreductase'],[ 'AHY39286', 'Dihydroprymidine dehydrogenase domain II, 4Fe-4S cluster']] 中的正确基因描述,使用具有最高r 值的基因id 作为示例
  • 您不能更简单地使用set 或更有效地使用heapq 来实现代码的第一部分吗?

标签: python list for-loop if-statement append


【解决方案1】:

尝试改变循环的顺序

  for c in top50:
    for d in geneanno:

目前,annotation 与文件中出现键相关的顺序

【讨论】:

  • 谢谢!有效!你介意解释一下背后的原因吗?我不明白更改顺序如何影响输出
  • @SeahJiaHui 你有未排序的列表geneanno(例如它的第一行包含d[0] = 'AHY40589'然后你正在步行扔top50,寻找这个带有条件if c[1] in d[0]:的键(注:d [0] 将是相同的迭代)并把值 d[1][:-1]。所以它只尊重第一个循环中列表的顺序
  • @SeahJiaHui 尝试运行此代码以了解它 for d in geneanno: for c in top50: print("c[1]", c[1], "d[0]", d [0]) 然后更改循环顺序并再次运行代码
【解决方案2】:

如果我正确理解了您想要的输出并且您希望注释是来自geneanno的文本,按top50 中的相应条目位置排序,那么您可以使用insert-

for d in geneanno:
    for i, c in enumerate(top50):
        if d[0] in c:
            annotations.insert(i, d[1][:-1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2018-08-05
    相关资源
    最近更新 更多