Python将多行放入数组

标签 python arrays line

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

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"等等]

如有任何帮助,我们将不胜感激。

最佳答案

您的数据已在列表中。如果您想以数组表示法打印出来,请替换为:

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()))

关于Python将多行放入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7753226/

相关文章:

Python MySQLdb 从另一个数据库中选择并插入

java - 简单的数组类工作但给出错误的输出

sql - PostgreSQL 第二个查询基于第一个查询的数组类型结果。即用数组链接查询

javascript - 当我使用 firefox 时,textarea 上的灰色边框线

routes - 如何初始化传单路由线

python - 检测和诊断无声崩溃的 worker

python - NumPy - 删除包含相同元素的子数组

python - "Dimensions must match"与 toco 的 tflite 转换错误

javascript - 获取多维数组中的值

python - 如何在Python程序中使用两个!=中断?