如何增加字母数字值 [英] How to increment alpha numeric values
问题描述
目前,我正在开发一个程序.我希望它增加5个字符的字母数字值. (很抱歉,如果增量不是正确的单词.)
Currently I'm working on a program. I'd like for it to increment a 5 character alpha numeric value. (Sorry if increment is not the correct word.)
所以我想让程序说从55aa0开始,到99zz9结束.我希望它从55aa0开始而不是00aa0开始的原因是因为对于我正在做的事情,这是浪费时间.
So I'd like for the program to say start at 55aa0 and end at 99zz9. The reason I'd like for it to start at 55aa0 and not 00aa0 is because for what I'm doing it'd be a waste of time.
我还想将该值分配给一个变量,并将其附加到另一个变量的末尾,并调用该URL.
I'd also like to assign that value to a variable and append it onto it onto the end of another variable and call this one url.
例如,URL可能是:domain.de/69xh2
So for example the url could be: domain.de/69xh2
如果您需要更多信息,我会很乐意添加.
If you need anymore information I'll gladly add it.
count = 0
while count <= n:
url = ""
if url.endswith(".jpg"):
fileType = ".jpg"
elif url.endswith(".png"):
fileType = ".png"
if os.path.isfile("images/" + fileName):
pass
else:
urllib.urlretrieve(url, "images/" + count + fileType)
count = count + 1
推荐答案
This sounds like a job for itertools
:
from itertools import dropwhile, islice, product
from string import digits, ascii_lowercase as letters
def values():
"""Yield strings in format '00aa0', starting with '55aa0'."""
def pred(t):
"""Return False once second digit in tuple t reaches '5'."""
return t[1] < '5'
for t in dropwhile(pred, product(digits[5:], digits, letters,
letters, digits)):
yield "".join(t)
这开始于(根据Simon的建议使用list(islice(values(), 0, 21))
):
This starts with (using list(islice(values(), 0, 21))
per Simon's suggestion):
['55aa0', '55aa1', '55aa2', '55aa3', '55aa4', '55aa5',
'55aa6', '55aa7', '55aa8', '55aa9', '55ab0', '55ab1',
'55ab2', '55ab3', '55ab4', '55ab5', '55ab6', '55ab7',
'55ab8', '55ab9', '55ac0']
为此使用itertools
的一个优点是,您不必在内存中构建整个(304,200个元素)列表,但可以对其进行迭代:
An advantage of using itertools
for this is that you don't have to build the whole (304,200-element) list in memory, but can iterate over it:
for s in values():
# use s
请注意,此版本与您的要求紧密相关(向Krab提示以提高效率),但可以轻松对其进行修改以更广泛地使用.
Note that this version is pretty tightly coupled to your requirements (hat tip to Krab for efficiency improvement), but it could easily be modified for more general use.
一个更快的版本,再次来自Krab的建议:
An even faster version, again from Krab's suggestion:
def values():
"""Yield strings in format '00aa0', starting with '55aa0'."""
for t in product(map(str, range(55, 100)), letters, letters, digits):
yield "".join(t)
注意:在Python 2.x中使用xrange
和itertools.imap
.
Note: use xrange
and itertools.imap
in Python 2.x.
这篇关于如何增加字母数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!