[英]Removing small words in python from nested lists
在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
你可以使用嵌套列表理解,就像這樣
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]
這是一個代碼示例,而不僅僅是打印。 原始但有效: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)
編輯:另一個答案可能更好。 但是這個也有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.