Skip to main content
 首页 » 编程设计

Python将多行放入数组

2025年05月04日1852php

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

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