根据某些值选择表的某些行

时间:2019-12-05 17:36:10

标签: python dictionary

所以我有这张桌子:

enter image description here

我想得到以下结果:

enter image description here

所以我做了这段代码:

table_1=open(name_table,'r')
results=[]
for seq_id in table_1:
    seq_id=seq_id.strip()
    seq_id_1=seq_id.split('\t')
    results.append(seq_id_1)
results

dictionary={x: [v[1:] for v in results if v[0] == x] for x in set(y[0] for y in results)}
for items_file_key,items_file_value in dictionary.items():
    percentage = float(items_file_value[0][1])
    for value_1 in items_file_value:
        values_to_use=value_1[1] + ', ' + value_1[11]
        curValue = float(value_1[1])
        if  curValue >= percentage-0.05 or curValue <= percentage-0.05:
            write_to = values_to_use
            dictionary[items_file_key] = write_to

但是使用这个字典,我只能得到条目的第一个值,就像这样:

{'12':'97.7,Car','11:99,Dog1} 

,我想这样:

{'12':['97.8,Car','97.8 Car1','97.8,Car3'], 
 '11':['11,99,Dog1','11,99,Dog2']

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

这可以通过在字典中跟踪seq_ids的不同值,然后将数据附加到特定的seq_id来完成。检查以下内容:

table_1=open(name_table,'r')
results=[]
for seq_id in table_1:
    results.append(seq_id.strip().split('\t'))

data = dict()

for row in results:
    key = row[0]
    value = ','.join(row[1:])
    if row[0] not in data:
        data[key]=[]
    data[key].append(value)

print(data)