所以我的输入数据是这样的字符串列表:
coordIndex =
[' 8, 9, 6, 4, 2, 0, -1,',
' 11, 1, 3, 5, 7, 10, -1,',
' 1, 11, 8, 0, -1,',
' 3, 1, 0, 2, -1,',
' 5, 3, 2, 4, -1,',
' 7, 5, 4, 6, -1,',
' 10, 7, 6, 9, -1,',
' 11, 10, 9, 8, -1']
然后 应该是这样的int元组:
coordIndex=
[[8, 9, 6, 4, 2, 0],
[11, 1, 3, 5, 7, 10],
[1, 11, 8, 0],
[3, 1, 0, 2],
[5, 3, 2, 4],
[7, 5, 4, 6],
[10, 7, 6, 9],
[11, 10, 9, 8]]
我能够清除空白,摆脱逗号,通过执行以下操作解析为int:
coordIndex = [x.replace(' ','') for x in coordIndex]
coordIndex = [x.replace(',-1,','') for x in coordIndex]
coordIndex = [x.replace(',-1','') for x in coordIndex]
coordIndex = [x.replace(',',' ') for x in coordIndex]
coordIndex = [x.rstrip() for x in coordIndex]
j = 0
for items in coordIndex:
coordIndex[j] = tuple(map(int, items.split(' ')))
j+=1
但是我在输入数据的新行中出现“ -1”问题。 “ -1”始终是我必须创建的每个元组行的分隔符,但我看不到如何在python中实现。
如果有人有主意,将不胜感激。谢谢!
答案 0 :(得分:2)
您可以执行以下操作:
[list(map(int,tuple(i.replace(' ','').split('-1')[0].split(',')[:-1]))) for i in s]
[(18, 19, 7, 8),
(19, 10, 6, 7),
(10, 11, 5, 6),
(11, 12, 4, 5),
(12, 13, 3, 4),
(13, 14, 2, 3),
(14, 15, 1, 2),
(15, 16, 0, 1),
(16, 17, 9, 0),
(17, 18, 8, 9),
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 5),
(19, 18, 17, 16, 15, 14, 13, 12, 11, 10)]
答案 1 :(得分:0)
我建议不要逐行读取文件,因为您基本上需要用另一种方法进行enline解析。想想:
with open('datafile.txt') as f:
data = f.read()
data = data.replace(' ', '').replace(',\n', '')
lines = data.split(',-1'))
index = [tuple(l.strip(',').split(',')) for l in lines if l]