开发者

Remove a '\n' list item from a python list

I have a list which contains an item '\n' in it. I want to remove it. however, the remove command is not working for it. Can anyone tell me what I am doing wrong?

def main():
    list1 = ['\ng,g\ng,g,g\n', '\n', '\ns\ns,s\n', '\nd,d\nd\nd,d,d,d\n开发者_运维知识库\n']
    print list1

    print list1.remove('\n')


if __name__ == '__main__':
    main()

Also, if my list were to contain many such entries '\n', how do I remove them all? I currently use set() to get the duplicates and then am trying to get the remove command to work. However, the set() command seems to change the sorting of the list. I'd rather iterate through the list and incase a '\n' is found, remove it.


The remove method modifies the list in-place and returns None. Thus, when you use print list1.remove('\n'), the list is modified, but None is printed. Do it in two steps, instead:

list1.remove('\n')
print list1

To remove all occurrences, most natural would be to construct a new list while excluding the newlines. For example:

list2 = [a for a in list1 if a != '\n']

If it must be in-place for some reason, then repeatedly use list1.remove until an exception is raised:

while True:
    try:
        list1.remove('\n')
    except ValueError:
        break


this will remove all of them:

list1=filter(lambda x: x != '\n', list1)


Removing stuff from a list is one of the many uses of list comprehensions:

no_n = [x for x in list1 if x != '\n']
# to change the original list
list1[:] = no_n


list1 = ['\ng,g\ng,g,g\n', '\n', '\ns\ns,s\n', '\nd,d\nd\nd,d,d,d\n\n']
list2 = []

list2 = [el.replace('\n', '') for el in list1]

print list2
   >>> 
['g,gg,g,g', '', 'ss,s', 'd,ddd,d,d,d']


It works here:

def main():
    list1 = ['\ng,g\ng,g,g\n', '\n', '\ns\ns,s\n', '\nd,d\nd\nd,d,d,d\n\n']
    print list1
    list1.remove('\n')
    print list1


if __name__ == '__main__':
    main()

Try it here: http://codepad.org/YXHOHgwv

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜