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

条带和格式坐标对

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

    test 我想转换成字符串格式

    print(test)
    [[[-122.45939656328747, 37.796690447896445], [-122.45859061899071, 37.785810199890264], [-122.44198816647757, 37.786535549757346], [-122.43578239539256, 37.789920515803715], [-122.42828711343275, 37.77444638530603]]]
    

    预期输出为

     "-122.45939656328747, 37.796690447896445 | 122.45859061899071, 37.785810199890264 | -122.44198816647757, 37.786535549757346 | -122.43578239539256, 37.789920515803715 | 
    -122.42828711343275, 37.77444638530603"
    

    下面的代码只删除外括号,如何使用python删除内括号并在坐标对之间放置管道(“|”)?

    import re
    print(str(test).strip('[]'))
    
    test = re.sub('[[]]', '', test)
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   LtChang    7 年前

    既然外括号在你的问题中似乎不重要,我就把它去掉 test[0] ,下面的代码应该给出您想要的。

    result = [str(coor).strip('[]') for coor in test[0]]
    result = " | ".join(result)
    
        2
  •  0
  •   Steve Archer    7 年前

    好吧,看起来你有一个包含一个项目的列表,这个项目是一个列表列表。有点奇怪,但还行。第一步是提取列表列表,非常简单,只需获取索引0。然后我要做的是将每个内部列表都变成一个字符串(而不是像上面那样将整个内容转换为字符串),并在大列表上使用join,如下所示:

    formatted = ' | '.join([str(pair) for pair in test[0]])
    

    编辑:意识到上面的答案会导致每一对都有括号,我猜你不会想要的。只需删除第一个和最后一个字符即可轻松修复:

    formatted = ' | '.join([str(pair)[1:-1] for pair in test[0]])