【问题标题】:How to increment alpha numeric values如何增加字母数值
【发布时间】:2014-01-22 11:18:32
【问题描述】:

目前我正在开发一个程序。我希望它增加一个 5 个字符的字母数值。 (对不起,如果增量不是正确的词。)

所以我想让程序说从 55aa0 开始,在 99zz9 结束。我希望它从 55aa0 而不是 00aa0 开始的原因是因为我正在做的事情是浪费时间。

我还想将该值分配给一个变量并将其附加到另一个变量的末尾并调用这个 URL。

例如,网址可以是:domain.de/69xh2

如果您需要更多信息,我很乐意添加。

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

【问题讨论】:

  • 你能说出正确的顺序是什么样的吗?会不会是,例如['55aa0', '55aa1', '55aa2', '55aa3', '55aa4', '55aa5', '55aa6', '55aa7', '55aa8', '55aa9', '55ab0' ...]
  • ['55aa0', '55aa1', ... '55aa9', '55ab0', ... '55az9', '55ba0', ... '55zz9', '56aa0', ...'59zz9','60aa0']

标签: python increment urllib


【解决方案1】:

这听起来像是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))):

['55aa0', '55aa1', '55aa2', '55aa3', '55aa4', '55aa5', 
 '55aa6', '55aa7', '55aa8', '55aa9', '55ab0', '55ab1', 
 '55ab2', '55ab3', '55ab4', '55ab5', '55ab6', '55ab7', 
 '55ab8', '55ab9', '55ac0']

为此使用itertools 的一个优点是您不必在内存中构建整个(304,200 个元素)列表,但可以对其进行迭代:

for s in values():
    # use s

请注意,此版本与您的要求非常紧密地耦合(向 Krab 致敬以提高效率),但可以轻松对其进行修改以用于更一般的用途。

一个更快的版本,同样来自 Krab 的建议:

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 中使用 xrangeitertools.imap

【讨论】:

  • +1:优雅的解决方案。并且要打印出列表,可以使用更多的 itertools 优点,例如print (list(itertools.islice(values(), 0, 100))) ... 打印前一百个项目(参见here)。
  • 在枚举产品之前进行过滤会更有效,这意味着使用digits[5:]之类的东西代替digits的前两种用法
  • 数字的第二次使用应该包括 0-4,例如当第一个数字是6,但可以应用于第一个
  • 哦,是的。我错过了。
  • 如果你不介意的话,我仍然不喜欢这里的 dropwhile。 :-) (str(x) for x in range(55,100)) 将是前两个 digits 实例的正确替换,这将消除对 dropwhile 的需要。我知道它在 OP 的设置中可能无关紧要,但根据我的测量,它仍然减少了函数运行时间的 1/4。
【解决方案2】:

我使用了两个整数从右到左逐位相加的基本算法。

def get_next(st):
    next_str = ""
    increment = '0'*(len(st)-1) + '1'
    index = len(st) -1
    carry = 0
    curr_digit = 0
    while(index>=0):
        if (st[index].isalpha()):

            curr_digit = (ord(st[index]) + int(increment[index]) + carry)
            if curr_digit > ord('z'):
                curr_digit -= ord('a')
                curr_digit %= 26
                curr_digit += ord('a')
                carry = 1
            else:
                carry = 0
            curr_digit = chr(curr_digit)
            next_str += curr_digit

        elif (st[index].isdigit()):
            curr_digit = int(st[index]) + int(increment[index]) + carry
            if curr_digit > 9:
                curr_digit %= 10
                carry = 1
            else:
                carry = 0
            next_str += str(curr_digit)
        index -= 1
    return next_str[::-1]

counter = 20

next_str = '55aa0'
while(counter > 0):
    next_str = get_next(next_str)
    print next_str
    counter -= 1

输出:

55aa1
55aa2
55aa3
55aa4
55aa5
55aa6
55aa7
55aa8
55aa9
55ab0
55ab1
55ab2
55ab3
55ab4
55ab5
55ab6
55ab7
55ab8
55ab9
55ac0

【讨论】:

    【解决方案3】:

    这取决于你想先增加什么(即末尾的数字、第一个字母、第二个字母或第一个数字),但我只会有单独的变量并将它们连接起来。我还建议从数组中调用您的字母:

        letters = ["a","b"..."y","z"]
        var firstNum = 55
        var firstLetter = letters[0]
        var secondLetter = letters[0]
        var scondNum = 0
    

    然后做一个循环,增加你想要的任何东西,然后连接。例如,如果你想先增加最后一个数字:

    varList = []
    for i in range(0, 100):
      varList.append(firstNum + firstLetter + secondLetter + (secondNum + i))
    

    然后你会在那个循环中插入另一个循环,增加第二个字母的索引,等等......

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 2016-12-07
      相关资源
      最近更新 更多