繁体   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