如何删除列表中多次出现的字符串? [英] how to remove multiple occurrences of a string within a list?

查看:54
本文介绍了如何删除列表中多次出现的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我有一个像'''0024'',''哈哈'','0024''这样的清单

和作为输出我想要[''哈哈'']


如果我

myList.remove(''0024'')

>
然后只删除'0024''的第一个实例。


似乎正常的表达式是救援,但我找不到

正确的工具。


谢谢!

bahoo

解决方案

这取决于你的应用程序,但是'set''可能真的是你想要的b $ b,而不是列表。


>> s = set([" 0024"," haha​​"," 0024"])
s



set([" 0024"," haha​​"])


>> s.remove(" 0024")
s



set([" haha​​])


4月3日,1:31 pm,Matimus < mccre ... @ gmail.comwrote:


这取决于你的应用程序,但''set''可能真的是你的

想要,而不是列表。


> s = set([" 0024"," haha​​" ;," 0024"])
s



set([" 0024"," haha​​"])>> ; s.remove(" 0024")


> s



set([" haha​​"])



如果需要,你也可以遍历列表,如下所示:


counter = 0

your_list = [" 0024"," haha​​"," 0024"]

for your in your_list :

如果我==''0024'':

your_list.pop(柜台)

柜台+ = 1

Mike




bahoo写道:





我有一个像[' '0024'',''哈哈'','0024'']

和输出我想要[''哈哈'']


如果我

myList.remove(''0024'')


然后只删除''0024''的第一个实例。


似乎正规表达式是救援,但我找不到

正确的工具。


谢谢!< br $> b $ b bahoo



很难想象在这里使用正则表达式。这是一个简单的

尝试:


def removeall(mylist,obj):

而mjist中的obj:

mylist.remove(obj)


或者,如果您不需要进行更改:


[x for m in mylist if x!= obj]


Tom


Hi,

I have a list like [''0024'', ''haha'', ''0024'']
and as output I want [''haha'']

If I
myList.remove(''0024'')

then only the first instance of ''0024'' is removed.

It seems like regular expressions is the rescue, but I couldn''t find
the right tool.

Thanks!
bahoo

解决方案

It depends on your application, but a ''set'' might really be what you
want, as opposed to a list.

>>s = set(["0024","haha","0024"])
s

set(["0024","haha"])

>>s.remove("0024")
s

set(["haha"])


On Apr 3, 1:31 pm, "Matimus" <mccre...@gmail.comwrote:

It depends on your application, but a ''set'' might really be what you
want, as opposed to a list.

>s = set(["0024","haha","0024"])
s


set(["0024","haha"])>>s.remove("0024")

>s


set(["haha"])

If you want, you can also loop over the list, like so:

counter = 0
your_list = ["0024","haha","0024"]
for i in your_list:
if i == ''0024'':
your_list.pop(counter)
counter += 1
Mike



bahoo wrote:

Hi,

I have a list like [''0024'', ''haha'', ''0024'']
and as output I want [''haha'']

If I
myList.remove(''0024'')

then only the first instance of ''0024'' is removed.

It seems like regular expressions is the rescue, but I couldn''t find
the right tool.

Thanks!
bahoo

It''s hard to imagine using regular expressions here. Here''s a simple
attempt:

def removeall(mylist,obj):
while obj in mylist:
mylist.remove(obj)

Or, if you don''t need the changes in place:

[x for x in mylist if x!= obj]

Tom


这篇关于如何删除列表中多次出现的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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