【问题标题】:How to get the last string in line, and insert it to array?如何获取最后一个字符串,并将其插入数组?
【发布时间】:2018-03-06 15:04:31
【问题描述】:

我有以下文件:

1 0x000 1555106270.959849 0x02b
0 0x3ff 1555106270.967866 0x02c
0 0x3fe 1555106270.975882 0x02d
0 0x3fd 1555106270.983898 0x02e
0 0x3fc 1555106270.991915 0x02f
0 0x3fb 1555106270.999931 0x000
0 0x3fa 1555106271.007947 0x001
0 0x3f9 1555106271.015964 0x002
0 0x3f8 1555106271.023980 0x003
0 0x3f7 1555106271.031997 0x004
0 0x3f6 1555106271.040013 0x005
0 0x3f5 1555106271.048029 0x006

(可能有更多行)。

我想获取每一行的最后一个字符串,并将其插入到数组中。

我尝试以下方法:

arr_int = []
i = 0
result_file = open('result.txt', 'r')
for line in result_file:
    line.split()
    arr_int[i] = int(line.split()[-1])
    ++i
print (arr_int[2])

我收到以下错误:

arr_int[i] = int(line.split()[-1])
IndexError: list assignment index out of range

【问题讨论】:

  • 我不确定这是不是问题,但++i 不会增加i
  • 某处有空行,可能在末尾?
  • @Elliot Roberts- 那是什么?
  • @Klaus D - 没有。
  • i += 1 但使用这样的变量通常被认为是非 Python 的。我会做for i, line in enumerate(result_file)

标签: python arrays for-loop line


【解决方案1】:

因为这是 python,所以没有 ++i,此外,python 不允许将数组分配给任意不存在的索引(与 javascript 不同)。

你需要做两件事。首先,使用append。其次,您需要为 int 指定基数(因为它不是基数 10):

arr_int.append(int(line.split()[-1], 16))

【讨论】:

    【解决方案2】:

    在分配列表期间您不需要索引访问。 python 中的列表不是您在 C 或 C++ 中所知道的数组:

    last_words = []
    
    with open('result.txt', 'r') as result_file:
        for line in result_file:
            last_words.append(int(line.split()[-1]), 16)
    
    print(last_words[2])
    

    【讨论】:

      【解决方案3】:

      arr_int 被定义为一个空数组,所以你不能索引它。请改用append

      arr_int.append(int(line.split()[-1]))
      

      【讨论】:

        【解决方案4】:

        我认为您可能会遇到空行。在访问元素之前尝试过滤掉空行。

        with open('result.txt', 'r') as result_file:
          for line in result_file:
            if line.split():
              arr_int.append(int(line.split()[-1]))
        

        【讨论】:

        • 我认为你假设一个空行,因为IndexError,但IndexError 实际上是由 OP 试图分配给空数组上的索引(arr_int = [] 然后稍后arr_int[i] = ...)。
        • @StevenRumbalski 你是对的。我没有考虑,但我的回答也解决了那部分
        【解决方案5】:

        Python 不允许就地赋值。你可以试试这个:

        final_data = [i.strip('\n').split()[-1] for i in open('file.txt')]
        

        【讨论】:

          猜你喜欢
          • 2021-03-05
          • 1970-01-01
          • 2021-07-18
          • 1970-01-01
          • 2011-07-07
          • 2011-08-17
          • 1970-01-01
          相关资源
          最近更新 更多