簡體   English   中英

如何刪除字符串列表中的特殊字符並將其拆分為單獨的元素

[英]How to remove special character in a list of string and split it into separate elements

我有一個像這樣的字符串列表:

list = ["A", "B", "C", "E", "0,2344 | 0,234 | 0,2345 | 0,265 | 0.2235 |"]

預期輸出應該是:

list = ["A", "B", "C", "E", "0,2344", "0,234", "0,2345", "0,265", "0.2235"]

誰能建議我一些方法來做到這一點?

從我從評論中了解到的。 你可以試試這個。

list_a=[j.strip() for i in list_a for j in i.split('|')] 

與問題無關:不要使用內置 / 關鍵字名稱作為變量名稱。

你需要:

new_list = []
for l in list1:
    y = l.split("|") 
    new_list.extend([j.strip() for j in y if j])

print(new_list)

輸出:

['A', 'B', 'C', 'E', '0,2344', '0,234', '0,2345', '0,265', '0.2235']

你可以做這樣的事情,

lst = ["A", "B", "C", "E", "0,2344 | 0,234 | 0,2345 | 0,265 | 0.2235 |"]

output = []
for item in lst:
    if item.find("|"):
        values = item.replace("|", "").strip().split()
        for value in values:
            output.append(value.strip())
    else:
        output.append(item)

print(output)

或者更好的是你可以像這樣使用列表理解

lst =[subitem.strip() for item in lst for subitem in item.split('|') if subitem]
print(lst)

輸出將是,

['A', 'B', 'C', 'E', '0,2344', '0,234', '0,2345', '0,265', '0.2235']

希望這可以幫助!

ans= ''.join(i for i in '["A", "B", "C", "E", "0,2344 | 0,234 | 0,2345 | 0,265 | 0.2235 |"]'. replace('|','","'));
ans= ''.join(i for i in ans. replace(',""',''))
print(ans.replace(' ',''))

上面的代碼給出了預期的輸出,如下所示。

["A","B","C","E","0,2344","0,234","0,2345","0,265","0.2235"]

請按以下步驟操作:

   list = ["A", "B", "C", "E", "0,2344 | 0,234 | 0,2345 | 0,265 | 0.2235 |"]

   new_list = new_list = [ch.strip() for word in list for ch in word.split('|')]
   new_list.remove('')

謝謝

I want to remove | character in the last element of list 1 and split last element of list 1 into last 5 elements of list 2 

嘗試這個

result = list[0:-1]+list[-1].replace(' ', '').strip('|').split('|')

暫無
暫無

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

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