代码之家  ›  专栏  ›  技术社区  ›  goetzmoritz

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

  •  0
  • goetzmoritz  · 技术社区  · 7 年前

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

    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']
    

    和 它应该是一个这样的整数元组:

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

    如果有人有主意,会非常感谢帮助。谢谢!

    2 回复  |  直到 7 年前
        1
  •  2
  •   yatu Sayali Sonawane    7 年前

    您可以执行以下操作:

    [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)]
    
        2
  •  0
  •   Slam    7 年前

    我建议不要一行一行地读取文件,因为您基本上需要另一种在线解析方法。想想:

    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]