根据项目的长度从列表中选择项目

编程入门 行业动态 更新时间:2024-10-20 03:15:07
本文介绍了根据项目的长度从列表中选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的物品清单很大(有时清单中可能包含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.

更多推荐

根据项目的长度从列表中选择项目

本文发布于:2023-11-10 22:23:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576623.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   长度   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!