簡體   English   中英

如何用子列表替換列表中的字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM