我有类似的东西:
1
2
3
4
5
6
我希望它有:
[[1,2,3],[4,5,6]]
我该怎么办?非常感谢
答案 0 :(得分:2)
使用列表理解
import os
src = """1
2
3
4
5
6"""
print [[int(x) for x in sub.split(os.linesep)] for sub in src.split(os.linesep*2)]
#special case if this is for windows and src is a string
print [[int(x) for x in sub.split('\n')] for sub in src.split('\n\n')]
将返回
[[1, 2, 3], [4, 5, 6]]
答案 1 :(得分:1)
试试这个:
input = '''1
2
3
4
5
6'''
def parse(string):
out = []
groups = string.split('\n\n') # Split by empty line
for group in groups:
out.append([item.strip() for item in group.split('\n')])
return out
print(parse(input))