当键与Python相同时,CSV中的特定行作为字典和逻辑

2024-10-06 02:39:59 发布

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

abc11  bvc  ex  123  456  somestuffhere
abc11  bvc  ex  456  476  somestuffhere
abc12  bvc  ex  173  426  somestuffhere
abc12  bvc  ex  426  496  somestuffhere
abc13  bvc  ex  143  796  somestuffhere
abc13  bvc  ex  743  896  somestuffhere

我试图把上面的CSV文件作为字典,{'abc11':['123','476'],'abc12':['173','496'],'abc13':['143','896']}。我希望第0列的值作为键,第3列和第4列的值作为键,当键相同时,只有最小值(或第3列)和最大值(或第4列)的值。我也不确定这些值是否最好是作为字典中的一个列表,因为我需要稍后用另一个列表检查这些值


Tags: 文件csv列表字典exbvcabc11当键
2条回答

你可以这样做:

d = {}

with open(file) as f:
   for line in f:
       if line.split()[0] not in d:
           d[line.split()[0]] = [line.split()[3],line.split()[4]]
       else:
           d[line.split()[0]] = [min(line.split()[3],d[line.split()[0]][0]), max(line.split()[4],d[line.split()[0]][1])]

您可以首先构建整个字典,其中的列表包含每个键的所有值。一旦字典建立起来,你就可以遍历每一个键,取最大值和最小值

yourdict = dict()

with open(file) as f:
   filedata = f.read().splitlines()
   for line in filedata:
       linedata = line.split()
       if linedata[0] not in yourdict:
           yourdict[linedata[0]] = []
       yourdict[linedata[0]].append(int(linedata[3]))
       yourdict[linedata[0]].append(int(linedata[4]))

for key in yourdict:
    yourdict[key] = [min(yourdict[key]), max(yourdict[key])]

另外,上面的文件不是CSV文件,CSV文件是逗号分隔的文件。你的文件是用空格分隔的,我的代码是用空格分隔的文件,而不是CSV。如果你真的有一个CSV文件,那么很容易改变

相关问题 更多 >