[英]How to replace a string inside a list with a sub-list
li = ['a', '#b', 'c']
repl = ['1', '2', '3']
我想用repl
子列表更改'#b'
,意思是,这是我想要的输出:
['a', ['1', '2', '3'], 'c']
到目前为止,这是我的尝试:
for i in li:
if i.startswith('#'):
i.replace(i, repl)
我收到此错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-151b36fac37c> in <module>()
1 for i in li:
2 if i.startswith('#'):
----> 3 i.replace(i, repl)
TypeError: Can't convert 'list' object to str implicitly
您不能用列表替换子字符串。 相反,使用推导式迭代列表:
li = ['a', '#b', 'c']
repl = ['1', '2', '3']
new_li = [repl if i.startswith('#') else i for i in li]
输出:
['a', ['1', '2', '3'], 'c']
如果您不想使用列表推导式,您可以写出整个泛型循环,或者使用函数式方法:
通用循环:
new_l = []
for i in li:
if i.startswith('#'):
new_l.append(repl)
else:
new_l.append(i)
函数式方法:
new_li = map(lambda x:repl if x.startswith('#') else x, li)
就地版本
li = ['a', '#b', 'c']
repl = ['1', '2', '3']
for i, item in enumerate(li):
if item.startswith('#'):
li[i] = repl
如果您不想使用列表理解:
li = ['a', '#b', 'c']
repl = ['1', '2', '3']
for count, i in enumerate(li):
if i.startswith('#'):
li[count] = repl
print li
['a', ['1', '2', '3'], 'c']
li = ['a', '#b', 'c']
repl = ['1', '2', '3']
x = li.index('#b')
li[x] = repl
print(li)
这应该会给出想要的结果
您还可以使用基于堆栈的方法:
li = ['a', '#b', 'c']
repl = ['1', '2', '3']
stack = []
for elem in li:
stack.append(elem)
if stack[-1].startswith("#"):
stack.pop()
stack.append(repl)
print(stack)
哪些输出:
['a', ['1', '2', '3'], 'c']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.