从python列表中删除'\ n'列表项 [英] Remove a '\n' list item from a python list

查看:1615
本文介绍了从python列表中删除'\ n'列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,其中包含项"\ n". 我要删除它.但是,remove命令不适用于该命令.谁能告诉我我在做什么错?

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()

此外,如果我的列表中包含许多这样的条目'\ n',我该如何将它们全部删除?我目前使用set()获取重复项,然后尝试使remove命令起作用.但是,set()命令似乎会更改列表的排序.我宁愿遍历列表,以防万一找到'\ n',将其删除.

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.

推荐答案

remove方法就地修改列表并返回None.因此,当您使用print list1.remove('\n')时,列表会被修改,但会打印None.而是分两个步骤进行操作:

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']

如果由于某种原因必须就位,则重复使用list1.remove直到引发异常:

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

这篇关于从python列表中删除'\ n'列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆