在两个独特字符之间创建列表[python]

时间:2016-03-15 13:42:32

标签: python list python-3.x for-loop

我有一个名为text2.txt的文件,如下所示:

20.0.60.129/29
20.0.60.129
20.0.60.130
20.0.60.131
20.0.60.132
20.0.60.133
20.0.60.134
20.56.32.78/29
20.56.32.73
20.56.32.74
20.56.32.75
20.56.32.76
20.56.32.77
20.56.32.78
20.0.100.73/29
20.0.100.73
20.0.100.0
20.0.100.75
20.0.100.76
20.0.100.77
20.0.100.78
20.0.241.30/29

我现在的代码是:

import ipaddress
import pprint
import re

lines = []
char1 = '/'
char2 = '/'
with open("text2.txt", 'r') as file:    
    for line in file:

        sep = (line[line.find(char1)+1 : line.find(char2)])     
        lines.append(sep.strip())

pprint.pprint(lines)        

我现在得到的结果看起来像这样

['',
 '20.0.60.129',
 '20.0.60.130',
 '20.0.60.131',
 '20.0.60.132',
 '20.0.60.133',
 '20.0.60.134',
 '',
 '20.56.32.73',
 '20.56.32.74',
 '20.56.32.75',
 '20.56.32.76',
 '20.56.32.77',
 '20.56.32.78',
 '',
 '20.0.100.73',
 '20.0.100.0',
 '20.0.100.75',
 '20.0.100.76',
 '20.0.100.77',
 '20.0.100.78',
 '']            

我希望得到一个如下所示的结果: (在每个空行之间代码应该开始一个新列表)

['20.0.60.129',
'20.0.60.130',
'20.0.60.131',
'20.0.60.132',
'20.0.60.133',
'20.0.60.134']

['20.56.32.73',
'20.56.32.74',
'20.56.32.75',
'20.56.32.76',
'20.56.32.77',
'20.56.32.78']

['20.0.100.73'
'20.0.100.0',
'20.0.100.75'
'20.0.100.76'
'20.0.100.77'
'20.0.100.78']

3 个答案:

答案 0 :(得分:0)

final_lines = [] 
for l in lines:
    if l == "":  
       newline = []
       if len(newline) != 0:
           final_lines.append(newline)
    else:
        newline.append(l)

我正在列出清单。由于行中有一个“”,我将列表中的列表追加到final_lines,否则继续将值添加到换行符,直到列表中再次遇到“”。

答案 1 :(得分:0)

# Get index of '' values:
indexes = [i for i, v in enumerate(lines) if v == '']

# Return lists by slicing main list
for index, _ in enumerate(indexes[:-1]):
    print lines[indexes[index] + 1:indexes[index + 1]]

答案 2 :(得分:0)

为您提出要求

  

在每个空行之间,代码应该开始一个新列表

你可以使用:

t = ['',
 '20.0.60.129',
 '20.0.60.130',
 '20.0.60.131',
 '20.0.60.132',
 '20.0.60.133',
 '20.0.60.134',
 '',
 '20.56.32.73',
 '20.56.32.74',
 '20.56.32.75',
 '20.56.32.76',
 '20.56.32.77',
 '20.56.32.78',
 '',
 '20.0.100.73',
 '20.0.100.0',
 '20.0.100.75',
 '20.0.100.76',
 '20.0.100.77',
 '20.0.100.78',
 '']


def get_result(t):
    # new list each time c == ""
    r = []
    for c in t:
        if c == "":
            yield r
            r = [] # reset list
        else:
            r.append(c)

for l in get_result(t):
    if l:
        print(l)

['20.0.60.129', '20.0.60.130', '20.0.60.131', '20.0.60.132', '20.0.60.133', '20.0.60.134']
['20.56.32.73', '20.56.32.74', '20.56.32.75', '20.56.32.76', '20.56.32.77', '20.56.32.78']
['20.0.100.73', '20.0.100.0', '20.0.100.75', '20.0.100.76', '20.0.100.77', '20.0.100.78']