简体   繁体   中英

Removing small words in python from nested lists

In python I've aa list named list_1 for the purpose of this question. 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. 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

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

Here is an code example, not just printing. Primitive but effective :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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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