根据项目的长度从列表中选择项目 [英] select items from a list based on length of the item

查看:57
本文介绍了根据项目的长度从列表中选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的物品清单很大(有时清单中可能包含100万个物品).现在,我想根据每个项目的长度来过滤此列表中的元素.即我要添加小于7个字符或大于24个字符的项目.我写的代码是:

I am having a big list of items (and the list may sometimes hold 1 million items). Now I want to filter elements in this list based on the length of each item. i.e. I want to add items which are either less than 7 chars or greater than 24 chars. The code which I wrote is:

returnNumbers //the list that holds million items
for num in returnNumbers:
    if((len(num)<7 or len(num)>24)):
        invalidLengthNumbers.append(num);

不确定是否有更好的方法,因为遍历一百万个项目很耗时间.

Not sure if there is a better way of doing this, as going thru 1 million items is time taking.

推荐答案

您确实想采用迭代方法.

You want to take an iterative approach, really.

您的代码可以用列表理解代替:

Your code can be replaced with a list comprehension:

invalidLengthNumbers = [num for num in returnNumbers if len(num) < 7 or len(num) > 24]

或者,通过利用比较链的优势,更短且只进行一次 len() 调用:

or, shorter and only taking one len() call by taking advantage of comparison chaining:

invalidLengthNumbers = [num for num in returnNumbers if not 7 <= len(num) <= 24]

但这只会更快一点.

如果以后需要遍历 invalidLengthNumbers ,请不要使用中介列表.直接循环并过滤 returnNumbers .也许甚至 returnNumbers 本身也可以由生成器代替,并且也可以迭代地过滤该生成器.

If you need to loop over invalidLengthNumbers later, don't use an intermediary list. Loop and filter over returnNumbers directly. Perhaps even returnNumbers itself can be replaced by a generator, and filtering that generator can be done iteratively too.

def produceReturnNumbers():
    for somevalue in someprocess:
        yield some_other_value_based_on_somevalue

from itertools import ifilter

for invalid in ifilter(lambda n: not 7 <= len(n) <= 24, produceReturnNumbers()):
    # do something with invalid

现在您不再拥有一百万个项目的列表.您有一个生成器,可以根据需要生成一百万个项目,而不将其全部保存在内存中.

Now you no longer have a list of 1 million items. You have a generator that will produce 1 million items as needed without holding it all in memory.

这篇关于根据项目的长度从列表中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆