如何在没有任何内容的情况下替换python列表中的所有零?

时间:2016-06-24 09:09:04

标签: python

我需要在没有任何内容的情况下替换newsplitted中的零。基本上,我需要删除它们。如何在没有进口的情况下这样做?有人可以帮忙吗?

input_string = "01-result.xls,2-result.xls,03-result.xls,05-result.xls" 
# Must be turned into ['result1','result2', 'result3', 'result5']

splitted = input_string.split(',')

newsplitted =  ["".join(x.split('.')[0].split('-')[::-1]) for x in splitted ]

这是我到目前为止所尝试的:

final = []
for Y in newsplitted :
      final =[Y.replace('0','')]

只是为了学习,如果我想在另一个for循环中完成替换部分,那怎么会这样做?

3 个答案:

答案 0 :(得分:2)

具有列表理解的一个班轮

input_string = "01-result.xls,2-result.xls,03-result.xls,05-result.xls"

result = [''.join(i.split('-')[::-1]).replace('.xls', '').replace('0', '') for i in input_string.split(',')]

结果

['result1', 'result2', 'result3', 'result5']

这与

基本相同
result = []
for i in input_string.split(','):
    formatted_element = ''.join(i.split('-')[::-1]).replace('.xls', '').replace('0', '')
    result.append(formatted_element)

在你的情况下你应该这样做:

[Y.replace('0', '') for Y in newsplitted]

final = []
for Y in newsplitted :
      final.append(Y.replace('0',''))

我建议你阅读更多关于python中列表推导的内容

http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/

您可以随时参考文档

https://docs.python.org/3.5/tutorial/datastructures.html#list-comprehensions

答案 1 :(得分:1)

使用内置map方法:

newsplitted =  ['result01', 'result2', 'result03', 'result05']
result = map(lambda x: x.replace('0', ''), newsplitted)

当你想对每个人做同样的事情时,使用 map()是很好的做法 你的iterable中的项目。

答案 2 :(得分:1)

input_string = "01-result.xls,2-result.xls,03-result.xls,05-result.xls" 
result = [el[el.index('-')+1:]+el[el.index('-')-1] for el in input_string.replace(".xls","").split(',')]

结果是:

['result1', 'result2', 'result3', 'result5']