Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我将如何进行自动名称生成_Python_Combinations_Combinatorics - Fatal编程技术网

Python 我将如何进行自动名称生成

Python 我将如何进行自动名称生成,python,combinations,combinatorics,Python,Combinations,Combinatorics,对于我的项目,我需要通过一个文件,我找到的每辆车,我必须用3个字母和2个数字命名。例:ABC01。我该如何编写一个函数来自动生成这样的名称,例如,它从AAA01开始,一直到AAA99,然后再到AAB01,依此类推,直到我没有车来命名为止。我的问题只是如何让一个函数生成这些名称,我可以创建if语句来检查是否还有汽车需要命名。非常感谢 对这一点有好处: from itertools import product import string pools = [string.ascii_upperca

对于我的项目,我需要通过一个文件,我找到的每辆车,我必须用3个字母和2个数字命名。例:ABC01。我该如何编写一个函数来自动生成这样的名称,例如,它从AAA01开始,一直到AAA99,然后再到AAB01,依此类推,直到我没有车来命名为止。我的问题只是如何让一个函数生成这些名称,我可以创建if语句来检查是否还有汽车需要命名。非常感谢

对这一点有好处:

from itertools import product
import string

pools = [string.ascii_uppercase]*3 + [string.digits]*2
names = (''.join(c) for c in product(*pools) if c[-2:] != ('0', '0'))
# next(names) will give you the next unused name
例如:

>>> next(names)
'AAA01'
>>> next(names)
'AAA02'
>>> next(names)
'AAA03'

使用
itertools.product

from string import ascii_uppercase
from itertools import product

def my_key_generator():
    letters = product(ascii_uppercase, repeat=3)
    letters_nums = product(letters, range(1, 100))
    for letters, nums in letters_nums:
        yield '{}{:02}'.format(''.join(letters), nums)
然后检查:

from itertools import islice
keys = my_key_generator()
print list(islice(keys, 101))
# ['AAA01', 'AAA02', 'AAA03' [...snip...] 'AAA98', 'AAA99', 'AAB01', 'AAB02']
对于Python 3.3+

import string
from itertools import product

L = string.letters[26:]
I = map(str, range(10))
names = map("".join, itertools.product(L, L, L, I, I))
用法:

>>> for n in names:
>>>     print n


对于Python2.7+来说,你应该使用
itertools.imap
而不是
map

这真的很酷,我今年开始学习Python,所以我对模块等的知识目前有限,很高兴知道它相当容易操作,而且比我编写它的方式简单。
>>> from itertools import islice
>>> print(list(islice(names, 0, 10)))
['AAA00', 'AAA01', 'AAA02', 'AAA03', 'AAA04', 'AAA05', 'AAA06', 'AAA07', 'AAA08', 'AAA09']