繁体   English   中英

在Python中将非平凡的字符串输入转换为整数元组

[英]Converting non trivial String input into integer-tuple in python

所以我的输入数据是这样的字符串列表:

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中实现。

如果有人有主意,将不胜感激。 谢谢!

您可以执行以下操作:

[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)]

我建议不要逐行读取文件,因为您基本上需要用另一种方法进行内联分析。 考虑到:

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM