如何通过给定的分隔符在列表内拆分字符串并展平子字符串列表 [英] How to split strings inside a list by given delimiter and flatten the sub-strings lists
本文介绍了如何通过给定的分隔符在列表内拆分字符串并展平子字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有此列表的python脚本:
I have a python script with this list:
blocks = [
"item-1",
"item-2",
"item-3.0;item-3.1;item-3.2"
]
我已经尝试过了:
for (i, block) in enumerate(blocks):
if ";" in block:
[blocks.insert(i, c) for c in block.split(";")]
else:
blocks.insert(i, block)
要获取此信息:
blocks = [
"item-1",
"item-2",
"item-3.0",
"item-3.1",
"item-3.2"
]
不幸的是,我的代码不断覆盖列表中的元素,我只剩下这个了:
Unfortunately my code keeps overwriting the the elements in the list, and I'm left with this:
blocks = [
"item-1",
"item-2",
"item-3.2"
]
如何修改脚本以允许在列表内拆分字符串,然后将新的子字符串插入原始字符串的位置,而不会覆盖列表中的其他元素?
How can I modify the script to allow me to split a string inside of a list and then insert the new sub-strings into the position of the original string without overwriting the other elements in the list?
推荐答案
创建新列表可能会更容易:
It would probably be easier to make a new list:
blocks = [
"item-1",
"item-2",
"item-3.0;item-3.1;item-3.2"
]
new_blocks = []
for block in blocks:
for c in block.split(";"):
new_blocks.append(c)
# new_blocks = ['item-1', 'item-2', 'item-3.0', 'item-3.1', 'item-3.2']
这篇关于如何通过给定的分隔符在列表内拆分字符串并展平子字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文