本文介绍了Python使用itertools.product创建列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自范围列表的itertools创建一个列表,到目前为止,我已经做到了:

start_list = [xrange(0,201,1),xrange(0,201,2),xrange(0,201,5),xrange(0,201,10),xrange(0,201,20),xrange(0,201,50),xrange(0,201,100),xrange(0,201,200)]

现在,我知道如果我尝试运行下一行,它将杀死我的python解释器:

next_list = list(itertools.product(*start_list))

我想知道的是,是否有可能放入一个检查每个元组的参数,以获取其项的总和,并且仅在等于一定数量时才将它们放入 next_list ? /p>

也许像这样:

next_list = list(itertools.product(*start_list,sum(tuples)=200))

我知道这是不对的,我可能需要重新考虑我的处理方式.生成器中start_list的范围是否太多而无法建立另一个列表?

解决方案

更好地使用列表理解

new_list = [item for item in itertools.product(*start_list) if sum(item) == 200]

I'm creating a list with itertools from a list of ranges, so far I have this:

start_list = [xrange(0,201,1),xrange(0,201,2),xrange(0,201,5),xrange(0,201,10),xrange(0,201,20),xrange(0,201,50),xrange(0,201,100),xrange(0,201,200)]

Now, I know that if I were to try to run this next line it will kill my python interpreter:

next_list = list(itertools.product(*start_list))

What I'm wondering is would it be possible to put in an argument that checks each tuple, for a sum of its items and only puts them in next_list if equal to a certain amount?

Maybe something like:

next_list = list(itertools.product(*start_list,sum(tuples)=200))

I know this isn't right and I might need to start to re-think the way I'm going about this. Will start_list's ranges in the generator be too many to get through to build another list?

解决方案

Better to just use a list comprehension

new_list = [item for item in itertools.product(*start_list) if sum(item) == 200]

这篇关于Python使用itertools.product创建列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:31