使用条件在字典列表中搜索以提取特定元素

2024-09-29 23:30:17 发布

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

我有一个巨大的电子表格,我正试图搜索一些特定的数据。你知道吗

一方面我有这样的身份证:

Y00988-11    
G01024-14    
Z01933-13

另一方面,我有一个巨大的电子表格(CSV),格式如下:

Run,Sample,Source,Rate,
DFT,G01024-14,A,High
DFT,U04424-15,B,Low
TFF,T64673-18,A,Low
RRT,I01324-14,A,High
RRT,J01624-14,A,High
...

我试图提取感兴趣的ID的SampleID和Run。你知道吗

我使用内置阅读器将csv电子表格读入字典,但在提取感兴趣的元素时遇到了问题。你知道吗

import csv
import sys

# IDs of interest
dataset=sys.argv[1]

# CSV spreadsheet
database=sys.argv[2]

sampleIDs=[]
with open(dataset, 'r') as file:
    for line in file:
        line.strip('\n')
        sampleIDs.append(line)
file.close()

seq_Dict=[]
finalList=['init']


with open(database, 'rb') as csvfile:
    reader=csv.DictReader(csvfile, delimiter=',')
    for line in reader:
        seq_Dict.append(line)
csvfile.close()


for element in seq_Dict:
    for key, value in element.items():
        if element['Sample'] in sampleIDs:
            finalList.pop()
            finalList.append(element['Sample']+" "+element['Run'])

for i in finalList:
    print(i)

这个脚本返回sampleid中最后一个ID的信息,这样我就可以看到在循环期间发生的事情正在覆盖上一个迭代。 所以我用了deepcopy,但没用。你知道吗


Tags: csvsampleruninforsyslineelement
2条回答

有了你提供给我的新信息,这就是你被封锁的原因。你知道吗

for element in seq_Dict:
for key, value in element.items():
    if element['Sample'] in sampleIDs:
        finalList.pop()
        finalList.append(element['Sample']+" "+element['Run'])

这里finalList.pop()从数组中删除一个对象,而不是添加一个,这就是为什么只看到最后一个对象。你知道吗

同样,这也是无用的,因为循环for element in seq_Dict:中没有任何内容。只使用for element in seq_Dict:,因为您不接触keyvalue

for element in seq_Dict: 
for key, value in element.items():
    if element['Sample'] in sampleIDs:

最后,这是我建议你的最后一个版本。你知道吗

for element in seq_Dict:
    if element['Sample'] in sampleIDs:
        finalList.append(sample +" "+element['Run'])

试试这个:

for element in seq_Dict:
   sample = element['Sample']
   if sample in sampleIDs:
       finalList.append(sample +" "+element['Run'])

相关问题 更多 >

    热门问题