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

2024-09-30 04:39:29 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

Tags: the方法代码编辑列表lencounter单词
2条回答

这里是一个代码示例,而不仅仅是打印。原始但有效: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)

编辑: 另一个答案可能更好。但这个也行。你知道吗

可以使用嵌套列表理解,如下所示

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

这也可以用^{}函数编写,如下所示

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

相关问题 更多 >

    热门问题