2024-06-28 19:22:07 发布
网友
对于我的项目,我需要通过一个文件,每一辆车,我发现我必须用3个字母和2个数字命名。例如:ABC01。我该如何编写一个函数来自动生成这样的名称,例如,它从AAA01开始,一直到AAA99,然后再到AAB01,依此类推,直到我没有车可以命名为止。我的问题是如何让一个函数产生这些名字,我可以创建if语句来检查是否还有汽车留下来命名。非常感谢。你知道吗
对于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
或者
>>> from itertools import islice >>> print(list(islice(names, 0, 10))) ['AAA00', 'AAA01', 'AAA02', 'AAA03', 'AAA04', 'AAA05', 'AAA06', 'AAA07', 'AAA08', 'AAA09']
对于python2.7+,应该使用itertools.imap而不是map。你知道吗
itertools.imap
map
^{}有助于:
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。。。你知道吗
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+
用法:
或者
对于python2.7+,应该使用
itertools.imap
而不是map
。你知道吗^{} 有助于:
例如:
使用
itertools.product
。。。你知道吗然后检查:
相关问题 更多 >
编程相关推荐