Reputation: 31
In python I've a a 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
Upvotes: 0
Views: 257
Reputation: 2682
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.
Upvotes: 0
Reputation: 239483
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]
Upvotes: 3