[英]Python remove anything under 2 characters long
I have a list of strings (As below format) 我有一个字符串列表(如下格式)
['email', 'go', 'a', 'instance', 'at', 'boo', 'email', 'message', 'message', 'instance', 'at', 'hello']
How can i eliminate anything under two characters long? 如何消除两个字符以下的字符?
Using list comprehension is often the most readable: 使用列表理解通常是最易读的:
myList = ['email', 'go', 'a', 'instance', 'at', 'boo', 'email', 'message', 'message', 'instance', 'at', 'hello']
myResultList = [x for x in myList if len(x) >=2]
List Comprehension , is a mean to create a new list from iterating on another list. List Comprehension ,是一种通过迭代另一个列表来创建新列表的方法。 In my exemple for each x in myList, the list comprehension keep x if len(x) <= 2.
在我的示例中,对于myList中的每个x,如果len(x)<= 2,则列表理解将保留x。
you could also do things like: 您还可以执行以下操作:
myResultList = [x + "!oh" for x in myList if len(x) ==2]
that would results in ['go!oh','at!oh','at!oh']
会导致
['go!oh','at!oh','at!oh']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.