从嵌套列表中删除python中的小单词

时间:2014-03-11 00:48:31

标签: python list

在python中,我有一个名为list_1的列表,用于此问题。 嵌入该列表中的是一些较小的列表。 我想逐个浏览每个列表并删除任何小于3个字符的单词。 我已经尝试了很多方法,并且没有提出任何可以工作的方法。 我想我可能能够创建一个循环遍历每个单词并检查它的长度,但我似乎无法得到任何工作。

建议欢迎。

编辑:使用代码结束

while counter < len(unsuitableStories): #Creates a loop that runs until the counter is the size of the news storys.

    for word in unsuitableStories[counter]:


        wordindex = unsuitableStories[counter].index(word)
        unsuitableStories[counter][wordindex-1] = unsuitableStories[counter][wordindex-1].lower()

        if len(word) <= 4:

            del unsuitableStories[counter][wordindex-1]



    counter = counter + 1 # increases the counter

2 个答案:

答案 0 :(得分:2)

您可以使用嵌套列表理解,例如

lists = [["abcd", "abc", "ab"], ["abcd", "abc", "ab"], ["abcd", "abc", "ab"]]
print [[item for item in clist if len(item) >= 3] for clist in lists]
# [['abcd', 'abc'], ['abcd', 'abc'], ['abcd', 'abc']]

这也可以用filter函数编写,就像这样

print [filter(lambda x: len(x) >= 3, clist) for clist in lists]

答案 1 :(得分:0)

这是一个代码示例,而不仅仅是打印。原始但有效:D

lst = []
lst2 = ['me', 'asdfljkae', 'asdfek']
lst3 = ['yo' 'dsaflkj', 'ja']

for lsts in lst:
    for item in lsts:
        if len(item) > 3:
            lsts.remove(item)

编辑: 另一个答案可能更好。但是这个也有效。