Python从列表中删除一个措辞字符串

时间:2016-02-18 14:09:47

标签: python

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

4 个答案:

答案 0 :(得分:5)

你可以这样做:

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

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

答案 1 :(得分:2)

您可以使用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()]

答案 2 :(得分:1)

功能性编程方式:

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

答案 3 :(得分:-1)

以下是每个列表的逻辑,您可以循环使用

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

输出

['hey you']