干净的方式将元组连接到字符串

时间:2017-11-24 11:42:35

标签: python string tuples

是否有更清晰,更Pythonic的方法在元组值列表中执行以下操作:

list_stops = [(-122.4079,37.78356),
              (-122.404,37.782)]
str_join = ''
for i in list_stops:
    coords_str = str(i[0]) + ',' + str(i[1]) + ';'
    str_join = str_join + coords_str

final_str = str_join[:-1]

我需要获取一个连接所有元组值的字符串,但这些对需要用';'分隔标志。 我的“final_str”的输出示例:

-122.4079,37.78356;-122.404,37.782

3 个答案:

答案 0 :(得分:3)

第二链str.join,注意使用map必要条件将值转换为string

list_stops = [(-122.4079,37.78356),
              (-122.404,37.782)]
";".join(",".join(map(str, x)) for x in list_stops)

'-122.4079,37.78356;-122.404,37.782'

答案 1 :(得分:3)

您甚至可以尝试列表理解如下:

';'.join([','.join([str(x) for x in y]) for y in list_stops])
o/p: '-122.4079,37.78356;-122.404,37.782
#Explanation
#1st i make something like ['-122.4079,37.78356', '-122.404,37.782'] by
#all inner tuples become ',' joined
#then ';' join those valuse

分为两个步骤以获得更清晰

list_1 = [','.join([str(x) for x in y]) for y in list_stops]
#['-122.4079,37.78356', '-122.404,37.782']
req_string = ';'.join(list_1)
#'-122.4079,37.78356;-122.404,37.782'

答案 2 :(得分:2)

如果他们总是成对:

list_stops = [(-122.4079, 37.78356), (-122.404, 37.782)]
final_str = ';'.join('{},{}'.format(p1, p2) for p1, p2 in list_stops)

print final_str

给你:

-122.4079,37.78356;-122.404,37.782

如果你需要确保只使用对,如果给出的参数数量不正确,这种方法将以ValueError停止。