【问题标题】:Python-Is it possible to index values in a specific line of a file?Python-是否可以在文件的特定行中索引值?
【发布时间】:2017-09-24 00:23:48
【问题描述】:

我打开了一个文件进行阅读并打印了所有行。

6,78,84,78,100

146,90,100,90,90

149,91,134,95,80

641,79,115,70,111

643,100,120,100,90

我需要获取每行的第一个数字来创建字典键。其余的数字是字典的值。有没有办法使用带有 for 循环的索引来抓取行中的每一件事?

我尝试过使用 readlines() ,但在其他方面变得过于复杂,我不会详细介绍。如果可能的话,我宁愿保持这些线条不变并对其进行迭代。

我试过了:

fo=open('tester.csv','r')
def search(fo):
    for line in fo:
        key=line[0]
        value= (line[1],line[2],line[3],line[4])

我希望我的最终输出是一个字典= {6: (78,84,78,100)}

【问题讨论】:

    标签: python-3.x file-io


    【解决方案1】:
    t = open("tester.csv", "r")
    tstuff = t.readlines()
    outdict = {}
    tstufflength = len(tstuff)
    for i in tstuff:
        thing1, thing2 = i.split(",", 1)
        realthing2 = thing2.strip("\n")
        outdict[thing1]=realthing2
    print(outdict)
    

    仅当线路都在不同的线路上时才有效。

    输出:

    {'6': '78,84,78,100', '149': '91,134,95,80', '643': '100,120,100,90', '146': '90,100,90,90', '641': '79,115,70,111'}

    【讨论】:

      【解决方案2】:

      你想得到这样的输出吗?

      输出:

      ['6', '1', '1', '6', '6']
      

      那么,

      f = open('data.csv')
      result = []
      for line in f:
          if line != '\n':
              result.append(line[0])
      
      print(result)
      

      【讨论】:

      • 你不能这样做,因为字典的键必须是唯一的。在您的示例中,行的前几行并不都是唯一的。
      • for line in f: [\ntab] dict[line[0]] = line[1:] 你可以这样做。但答案是:{'6': '43,100,120,100,90','', '1': '49,91,134,95,80},因为值为 '6' 的键将被键为 '6' 的最新行覆盖
      • 检查这个问题:stackoverflow.com/questions/10664856/… 可能有用。
      • 我需要它们都是整数。
      • @ocean.1234 :您应该知道这不是一个要求人们为您编写代码的地方。我们只是在这里为您提供帮助,而不是编写您的代码。
      猜你喜欢
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2020-05-18
      • 2015-09-10
      • 1970-01-01
      相关资源
      最近更新 更多