在Python中编制特定数字列表

时间:2017-02-18 19:08:15

标签: python permutation

我如何创建一个由4位数组成的所有可能数字的列表,并且只使用数字0,1,2,3,4和6?

4 个答案:

答案 0 :(得分:1)

其他可能的方法是我可以使用排列并将长度限制为4.此外,可以进行额外检查以确定数字是否以非零值开头。

from itertools import permutations
# Define possible choices of list 
mynums = '012346'
num4Digits = [int("".join(i)) for i in permutations(mynums, 4) if i[0] in '12346']
# Checking output
num4Digits

答案 1 :(得分:1)

您可以使用List Comprehension

list = [x for x in range(1000,6667) 
        if "5" not in str(x) and 
        "7" not in str(x) and 
        "8" not in str(x) and 
        "9" not in str(x)]

range(1000,6667)为您提供1000和6666之间的所有数字,条件检查每个数字(x)不包含任何5,7,8或9。

*确实有很多更好的方法可以做到这一点,但这样做有效,它更明显,你可以把它放在一行

修改

这是另一个,有点复杂但也有效。

exclude = ["5","7","8","9"]
filter_func = lambda x: not(any(s in str(x) for s in exclude))
list = filter(filter_func, range(1000,6667));

答案 2 :(得分:0)

使用itertools.product

it = itertools.product(*(4 * ((0,1,2,3,4,6),)))

这会创建一个迭代器,你可以循环它。请注意,这会创建前导零,如果您不想要它们,则必须发布流程。

另一种选择是使用numpy

>>> templ = np.arange(6)
>>> templ[-1] += 1
>>> templ = templ * 10**np.arange(4)[::-1, None]
>>> templ = np.ix_(*templ)
>>> result=np.sum(templ).ravel()

这会生成一个实际数字数组,此处前导零被删除,如果您不想要短于4位数字,则可以剪切前6 ^ 3个元素result[6**3:]

答案 3 :(得分:-1)

import itertools
stuff = [0, 1, 2, 3, 4, 6]
results=[]
for L in range(0, len(stuff)+1):
   for subset in itertools.combinations(stuff, L):
       results.append(subset)