问题描述
我正在尝试使用itertools.product
从0-9999
创建数字列表.我可以通过以下操作从0000-9999
创建列表:
I am trying to create a list of numbers from 0-9999
using itertools.product
. I am able to create a list from 0000-9999
by doing the following:
numbers = ['0','1','2','3','4','5','6','7','8','9']
itertools.product(numbers,numbers,numbers,numbers)
虽然我想要像0001
这样的条目,但我也想获取001
,01
和1
.
And while I want entries like 0001
, I would also like to get 001
, 01
, and 1
.
包括这些内容的最有效方法是什么?我应该拨打itertools.product(numbers,numbers,numbers)
和itertools.product(numbers,numbers)
的电话,然后以某种方式将它们与原始电话号码合并,还是有更清洁的方法?
What would be the most effective way to include these? Should I make calls to itertools.product(numbers,numbers,numbers)
and itertools.product(numbers,numbers)
and then somehow combine these with the original or is there a cleaner way?
如果我应该再打两个电话并合并,有人可以指出我的做法吗?我尝试使用.append()
,但是会引发此错误:
If I should make two other calls and combine, can someone point me towards how this would be done? I attempted to use .append()
, but it throws this error:
'itertools.product' object has no attribute 'append'
感谢您的帮助.
推荐答案
您可以使用嵌套的listcomp或genexp(出于显示目的,此处将其尺寸减小):
You could use a nested listcomp or genexp (reduced in size here for display purposes):
>>> numbers = ['0','1','2']
>>> [''.join(p) for n in range(1,4) for p in product(numbers, repeat=n)]
['0', '1', '2', '00', '01', '02', '10', '11', '12', '20', '21', '22', '000', '001', '002', '010', '011', '012', '020', '021', '022', '100', '101', '102', '110', '111', '112', '120', '121', '122', '200', '201', '202', '210', '211', '212', '220', '221', '222']
这篇关于合并itertools.product的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!