简体   繁体   English

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

[英]Removing small words in python from nested lists

In python I've aa list named list_1 for the purpose of this question. 在python中,我有一个名为list_1的列表,用于此问题。 Imbedded within that list is a number of smaller lists. 嵌入该列表中的是一些较小的列表。 I want to go through each of these lists one by one and remove any words that are smaller than 3 characters. 我想逐个浏览每个列表并删除任何小于3个字符的单词。 I've tried a number of methods and come up with nothing i can get working. 我已经尝试了很多方法,并且没有提出任何可以工作的方法。 I thought i may be able to create a loop that went through each word and checked it's length, but i can't appear to get anything working at all. 我想我可能能够创建一个遍历每个单词并检查它的长度的循环,但我似乎无法获得任何工作。

Suggestions welcome. 建议欢迎。

Edit: Ended up using code 编辑:使用代码结束

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

You can use nested list comprehension, like this 你可以使用嵌套列表理解,就像这样

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

This can also be written with filter function, like this 这也可以filter功能编写,就像这样

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

Here is an code example, not just printing. 这是一个代码示例,而不仅仅是打印。 Primitive but effective :D 原始但有效: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)

EDIT: The other answer is probably better. 编辑:另一个答案可能更好。 But this one works too. 但是这个也有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM