我的输入文件如下所示:

1_10001 1       10001   1       342     0       0       0       342
1_10002 1       10002   3       426     379     34      0       13
1_10003 1       10003   2       506     480     0       0       26
1_10004 1       10004   1       562     0       562     0       0


我想创建一个字典,其中第一个字段(1_10001等)是键,而2:8是值。我尝试了这个:

d = {}
with open("test.in") as f:
     for line in f:
             sep = line.split()
             d[sep[1]] = sep[2:]


它不会引发错误,但d看起来像这样:


  
    
      d
      {'1':['10010','1','634','0','634','0','0']}
    
  


我希望键为字符串“ 1_10001”等,而不是“ 1”。还有,其余的呢?我还尝试将2:8放入列表中,但这产生了错误:

TypeError:列表索引必须是整数,而不是list

我对python完全陌生,因此请原谅任何愚蠢的行为。谢谢。

最佳答案

Python中的列表从0开始索引。

尝试:

d = {}
with open("test.in") as f:
     for line in f:
             sep = line.split()
             d[sep[0]] = sep[1:]

关于python - 如何在python字典中将字段范围设置为值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21148122/

10-12 16:50
查看更多