[英]Python: list/array, remove doubled words string
I want to filter only elements that have only one word and make a new array of it.我只想过滤只有一个单词的元素并创建一个新数组。 How could I do this in Python?我怎么能在 Python 中做到这一点?
Array:大批:
['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']
NewArray should be: NewArray 应该是:
['somewhat', 'all', 'dictator', 'was', 'in']
try this尝试这个
a= ['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']
print([i for i in a if " " not in i])
Output: Output:
['somewhat', 'all', 'dictator', 'was', 'in']
filter the list with a list comprehension使用列表理解过滤列表
old_list = ['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']
new_list = [x for x in old_list if len(x.split()) == 1]
Returns:回报:
['somewhat', 'all', 'dictator', 'was', 'in']
Using re.match and filter使用 re.match 和 filter
import re
MATCH_SINGLE_WORD = re.compile(r"^\w+$")
inp = ['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']
out = filter(MATCH_SINGLE_WORD.match, inp)
print(list(out)) # If you need to print. Otherwise, out is a generator that can be traversed(once) later
This solution would handle \n or \t being present in word boundaries as well along with single whitespace character.该解决方案将处理出现在单词边界中的 \n 或 \t 以及单个空白字符。
If you want to handle leading and trailing whitespaces,如果你想处理前导和尾随空格,
import re
from operator import methodcaller
MATCH_SINGLE_WORD = re.compile(r"^\w+$")
inp = ['somewhat', 'all', 'dictator', 'was called', 'was', 'main director', 'in']
out = filter(MATCH_SINGLE_WORD.match, map(methodcaller("strip"), inp))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.