如果用“/”python分隔,则合并列表项

2024-10-02 20:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份现有的清单,里面有你开车方向的信息。标题有时用“/”分隔。我只想合并用斜杠分隔的列表项。在本例中,这将合并索引:5、7、9和11,并删除6、8和10。你知道吗

original_list = ['Keep', 'right', 'to continue on', 'Exit 18', ', follow signs for', 'Hoograven', '/', 'Lunetten', '/', 'Houten', '/', 'Nieuwegein', '']
output_list = ['Keep', 'right', 'to continue on', 'Exit 18', ', follow signs for', 'Hoograven/Lunetten/Houten/Nieuwegein', '']

我找不到一个好的解决方案来处理列表中不同数量的斜杠。有什么想法吗?你知道吗


Tags: toright列表foronexitlistkeep
2条回答

不是很好的解决方案,但应该可以。在某些情况下,它给出的结果与前面的答案不同(例如,斜杠作为original_list中的第一个和最后一个元素),这可能对您有好处:

original_list = ['/', '/', 'Keep', 'right', 'to continue on', 'Exit 18', ', follow signs for', 'Hoograven', '/', '/', '/', 'Lunetten', '/', 'Houten', '/', 'Nieuwegein', '', '/', '/']
new_list = []

for i in range(len(original_list)):
    if len(new_list) > 0 and i > 0 and (original_list[i] == '/' or original_list[i-1] == '/'):
        new_list[-1] += original_list[i]
    else:
        new_list.append(original_list[i])

print new_list

结果:

['//Keep', 'right', 'to continue on', 'Exit 18', ', follow signs for', 'Hoograven///Lunetten/Houten/Nieuwegein', '//']

这会将字符串连接在一起,然后使用replace删除斜杠周围的分隔符,然后再次将其拆分:

'@'.join(L).replace('@/@', '/').split('@')

用法如下:

>>> '@'.join(['Keep', 'right', 'to continue on', 'Exit 18', ', follow signs for', 'Hoograven', '/', 'Lunetten', '/', 'Houten', '/', 'Nieuwegein', '']).replace('@/@', '/').split('@')
['Keep', 'right', 'to continue on', 'Exit 18', ', follow signs for', 'Hoograven/Lunetten/Houten/Nieuwegein', '']

只要选定的分隔符不出现在字符串中,此操作就有效。你知道吗

相关问题 更多 >