繁体   English   中英

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

[英]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.

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