对于我的项目,我需要浏览一个文件,并且我发现的每辆车都必须使用 3 个字母和 2 个数字来命名。例如:ABC01。我将如何编写一个函数来自动生成这样的名称,例如它以 AAA01 开始并一直到 AAA99,然后它会转到 AAB01 等等,直到我用完汽车来命名。我的问题只是我如何让一个函数产生这些名称,我可以创建 if 语句来检查是否还有任何汽车要命名。万分感谢。
问问题
69 次
3 回答
3
itertools.product()
对此有好处:
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'
于 2012-11-30T16:42:04.607 回答
2
使用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']
于 2012-11-30T16:42:44.183 回答
0
对于 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']
对于 Python 2.7+,您应该使用itertools.imap
而不是map
.
于 2012-11-30T16:47:40.077 回答