簡體   English   中英

如何用其他字符串列表替換字符串?

[英]How can I replace a string with a list of other strings?

有沒有辦法做到這一點?

list = ['test inc', 'abc', '123 corp']
words_to_filter = ['inc', 'corp']
list.replace(words_to_filter,'')

我的預期結果應該是:

test, abc, 123

現在我得到:

TypeError: replace() argument 1 must be str, not list

怎么樣:

for i in range(len(list)):
    for word in words_to_filter:
         list[i] = list[i].replace(word, "").strip()

作為一個班輪:

list = [" ".join([x for x in item.split() if x not in words_to_filter]) for item in list]

您可以只使用字典而不是列表。

test_str = 'inc test'
  
lookp_dict = {"hi" : "hello", "test" : "untest"}
  
temp = test_str.split()
res = []
for wrd in temp:
    res.append(lookp_dict.get(wrd, wrd))
      
res = ' '.join(res)
  
print(str(res))

這是我能想到的最直接的方法:

old_list = ['test inc', 'abc', '123 corp']
words_to_filter = ['inc', 'corp']
new_list = [' '.join(w for w in p.split() if w not in words_to_filter) for p in old_list]
new_list
['test', 'abc', '123']

如果您願意,可以將嵌套列表推導式擴展為更長的形式:

new_list = []
for phrase in old_list:
    words = [word for word in phrase.split() if word not in words_to_filter]
    new_list.append(' '.join(words))

另請注意:

  • 您最初的理想 output 有123作為 integer 而不是字符串'123' 如果這是您真正想要的,那么添加另一個語句new_list = [int(s) if isdigit(s) else s for s in new_list]
  • 您最初使用list來保存您的列表。 使用其他東西,因為list是一個關鍵字,它可以咬你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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