li = ['a', '#b', 'c']
repl = ['1', '2', '3']
I want to change '#b'
with the repl
sublist, meaning, this is my desired output:
['a', ['1', '2', '3'], 'c']
This is my attempt so far:
for i in li:
if i.startswith('#'):
i.replace(i, repl)
I get this error:
---------------------------------------------------------------------------
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
You cannot replace a substring with a list. Instead, iterate over the list using a comprehension:
li = ['a', '#b', 'c']
repl = ['1', '2', '3']
new_li = [repl if i.startswith('#') else i for i in li]
Output:
['a', ['1', '2', '3'], 'c']
If you do not want to use list comprehension, you can either write out the entire generic loop, or use a functional approach:
Generic loop:
new_l = []
for i in li:
if i.startswith('#'):
new_l.append(repl)
else:
new_l.append(i)
Functional approach:
new_li = map(lambda x:repl if x.startswith('#') else x, li)
inplace version
li = ['a', '#b', 'c']
repl = ['1', '2', '3']
for i, item in enumerate(li):
if item.startswith('#'):
li[i] = repl
If you don't want to use list comprehension:
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)
this should give the desired result
You could also use a stack based approach:
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)
Which Outputs:
['a', ['1', '2', '3'], 'c']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.