簡體   English   中英

Python從列表中刪除一個措辭字符串

[英]Python remove one worded strings from list

words = [['hey', 'hey you'], ['ok', 'ok no', 'boy', 'hey ma']]

我有一個包含字符串的列表列表。 我理解如何從列表中刪除特定元素,但不知道如何刪除只有一個單詞的元素。 我想要的輸出是:

final = [['hey you'], ['ok no', 'hey ma']]

我正在嘗試但我認為這是完全錯誤的....

remove = [' ']
check_list = []

for i in words:
    tmp = []
    for v in i:
        a = v.split()
        j = ' '.join([i for i in a if i not in remove])
        tmp.append(j)

    check_list.append(tmp)
print check_list

你可以做:

words = [['hey', 'hey you'], ['ok', 'ok no', 'boy', 'hey ma']]
final = [[x for x in sub if ' ' in x.strip()] for sub in words]
# [['hey you'], ['ok no', 'hey ma']]

我只是在所有字符串中搜索空格。

你可以使用filter

for words in list_of_lists: 
    words[:] = list(filter(lambda x: ' ' in x.strip(), words))

或列表理解:

for words in list_of_lists:
    words[:] = [x for x in words if ' ' in x.strip()]

功能編程方式:

>>> words
[['hey', 'hey you'], ['ok', 'ok no', 'boy', 'hey ma']]
>>> map(lambda v: ' '.join(v),
    filter(lambda y: len(y) > 1, map(lambda x: x.split(), words[1])))
['ok no', 'hey ma']
>>> map(lambda z: map(lambda v: ' '.join(v),
    filter(lambda y: len(y) > 1, map(lambda x: x.split(), z))), words)
[['hey you'], ['ok no', 'hey ma']]

這是每個列表的邏輯,您可以循環使用

wordlist=['hey', 'hey you']
filter(None,  [ p if re.sub('\\b\\w+\\b', '', p) != '' else None for p in wordlist ])

產量

['hey you']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM