【问题标题】:Python put multiple lines to arrayPython将多行放入数组
【发布时间】:2011-10-13 11:11:14
【问题描述】:

我使用正则表达式搜索包含数据的文本文件。我得到与此类似的输出。 例如,这是我得到的:

36
37
36
36
36
76
39
36
68
36
56
36
36
36
...

我需要所有这些 36 都在这样的数组中 ['36', '36', ....] 示例代码如下。

#!/usr/bin/python

import re

log = re.compile('Deleted file number: first: (\d+), second (\d+), third (\d+), fourth (\d+), bw (\d+), value: ([\dabcdefx]+), secondvalue: ([\d.]+)LM, hfs: ([\d.-]+)ls')

logfile = open("log.txt", "r").readlines()

List = []

for line in logfile:
    m = log.match(line)
    if m:
        first       = int (m.group(1))
        second      = int (m.group(2))
        third       = int (m.group(3))
        fourth      = int (m.group(4))
        bw          = int (m.group(5))
        value       = int (m.group(6),0)
        secondvalue = float (m.group(7))
        hfs         = float (m.group(8))

        List.append(str(first)+","+str(second)+"," \
                   +str(third)+","+str(fourth)+"," \
                   +str(bw)+","+str(value)+"," \
                   +str(secondvalue)+","+str(hfs))

for result in List:
    print(result)

我可以使用 sys.stdout.write() 将其显示在与打印项相同的一行中, 但是我怎样才能将所有这些放入一个数组中,就像 array = [ "149", 149", "153", "153" 等等]

任何帮助将不胜感激。

【问题讨论】:

  • 您的代码的相关摘录将对我们有所帮助。您可以创建一个列表并将每个值附加到它。
  • 我得到的不是字符串,而是列
  • 为什么在将它们保存为数组中的字符串时将它们转换为int和float。数组可以简单地通过 [first, second, third, ...]
  • 代替 List.append(str(first)...) 做 List.extend([first, second..])。

标签: python arrays line


【解决方案1】:

您的数据已经在列表中。如果你想用数组表示法打印出来,替换这个:

for result in List:
    print(result)

用这个:

print List

您确实不应该将您的列表称为 List,尽管 - list 是一个保留字,而 List 很相似。

顺便说一句:

List.append(str(first)+","+str(second)+"," \
               +str(third)+","+str(fourth)+"," \
               +str(bw)+","+str(value)+"," \
               +str(secondvalue)+","+str(hfs))

如果你使用一些其他的 Python 特性,比如 join,会更容易理解:

List.append(",".join([first, second, third, fourth, bw, value, secondvalue, hfs]))

事实上,由于您的变量只是正则表达式中的组,您可以将整个内容缩短为:

List.append(",".join(m.groups()))

【讨论】:

    【解决方案2】:

    你试过了吗:

    print List
    

    如果你想在一个字符串中:

    result = str(List)
    

    【讨论】:

    • 我同意@Nick Johnson 关于命名问题的观点。
    • 并赞成他的回答,因为他的groups 建议将使您的代码更易于阅读。
    【解决方案3】:

    假设你拥有的是字符串:

    '"149" "149" "153" "153" "159" "159" "165" "165" "36" "36" "44"'
    

    (不清楚您如何使用正则表达式获取数据,因为您没有显示任何代码),请使用

    [x.strip('"') for x in '"149" "149" "153" "153" "159" "159" "165" "165" "36" "36" "44"'.split()]
    

    获取列表(不是数组,这是另一回事):

    ['149', '149', '153', '153', '159', '159', '165', '165', '36', '36', '44']
    

    如果你真正想要的一个数组(它只能存储数值,而不是你所显示的数字的字符串表示,使用):

    import array
    foo = array.array('i',(int(x.strip('"')) for x in '"149" "149" "153" "153" "159" "159" "165" "165" "36" "36" "44"'.split()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 2015-04-10
      相关资源
      最近更新 更多