反转字符串列表而不影响数值

时间:2018-01-02 15:44:16

标签: python

我有一个字符串列表。

arr = ['17 -> 16 -> 1 -> 8 -> 0', '5 -> 2 -> 3 -> 6 -> 0']

我想要反转字符串,我正在使用此代码:

x = arr[::-1]
x = x.replace(">-", "->")
x = x[5:]

但输出是:

arr = ['0 -> 8 -> 1 -> 61 -> 71', '0 -> 6 -> 3 -> 2 -> 5']

然而,我需要输出:

arr = ['0 -> 8 -> 1 -> 16 -> 17', '0 -> 6 -> 3 -> 2 -> 5']

5 个答案:

答案 0 :(得分:6)

您应该将字符串拆分为箭头字符,反向,然后将它们连接起来。这有效:

[' -> '.join(reversed(a.split(' -> '))) for a in arr]

答案 1 :(得分:2)

您可以使用map

arr = ['17 -> 16 -> 1 -> 8 -> 0', '5 -> 2 -> 3 -> 6 -> 0']
final_list = list(map(lambda x:' -> '.join(x.split(' -> ')[::-1]), arr))

输出:

['0 -> 8 -> 1 -> 16 -> 17', '0 -> 6 -> 3 -> 2 -> 5']

答案 2 :(得分:1)

基础知识用空格分割字符串,反转它,然后再将它重新粘在一起。

" ".join(reversed("1 -> 2 -> 3 -> 4 -> 5".split()))

然后每个人都做

for a in arr:
    print(" ".join(reversed(a.split())))

答案 3 :(得分:1)

作为替代方案,regex基于从字符串中提取数字:

>>> arr = ['17 -> 16 -> 1 -> 8 -> 0', '5 -> 2 -> 3 -> 6 -> 0']

>>> [' -> '.join(re.findall('\d+', a)[::-1]) for a in arr]
['0 -> 8 -> 1 -> 16 -> 17', '0 -> 6 -> 3 -> 2 -> 5']

这是有用的,因为数字之间的模式不同

此外,Daniel's answer的版本略有不同,未使用reverse

#                                 v  to reverse the list
>>> [' -> '.join(a.split(' -> ')[::-1]) for a in arr]
['0 -> 8 -> 1 -> 16 -> 17', '0 -> 6 -> 3 -> 2 -> 5']

答案 4 :(得分:0)

说明:

[x.split(" -> ")[::-1] for x in arr]将字符串拆分为->的字符串子列表,并使用列表解析将其反转

" -> ".join(..)将内部列表连接回字符串

arr = ['17 -> 16 -> 1 -> 8 -> 0', '5 -> 2 -> 3 -> 6 -> 0']

sub = [" -> ".join(x.split(" -> ")[::-1]) for x in arr]

print(sub)

输出

['0 -> 8 -> 1 -> 16 -> 17', '0 -> 6 -> 3 -> 2 -> 5']

编辑:在看到Daniel Rosemans split pattern后删除了过于复杂的剥离和改编的分割文本。

# sub = [" -> ".join([y.strip() for y in x.split("->")[::-1]]) for x in arr]