2016-12-24 55 views
1

好吧...我需要遍歷任意長度的字符串。因爲我不知道該如何解釋這也很好,我的意思是這樣的:通過數字的未知長度的字母進行迭代

def zip(string1,string1): 
    ... 

當與"a""ad"稱它會返回一個列表:

>>>zip("a","ad") 
["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","aa","ab","ac","ad"] 

我已經嘗試使用map(chr,range(ord('a'),ord('nb')+1))但我得到TypeError: ord() expected a character, but string of length 2 found,我不知道該從哪裏出發。有任何想法嗎?

+0

起初我有點困惑,因爲zip是一種實際的python方法。 – Fallenreaper

回答

4

就是這樣:

def zip_(start, end): 
    def __inc(s): 
     if not s: 
      return "a" 
     elif s[-1] != "z": 
      return s[:-1] + chr(ord(s[-1]) + 1) 
     else: 
      return __inc(s[:-1]) + "a" 

    s = start 

    yield s 
    while s != end: 
     s = __inc(s) 
     yield s 


print list(zip_("a", "ad")) 

幾點意見:

  1. 不要用這個詞zip作爲一個變量或函數的名稱,因爲它已被保留。
  2. 在解決方案zip_是一個生成器。我這樣做是爲了不將太多的數據保存在內存中。如果您需要一個確切的列表,只需按照我在print-statement中所做的那樣轉換它即可。
  3. 如果參數錯誤,該函數可能進入無限循環。例如,如果您致電zip_("b", "a")。但實際上,如果需要添加幾行,很容易修復。
+0

謝謝!這工作完美,我喜歡它也是一個發電機! – TheCompModder

1

這是一個基數爲26的數字系統,這裏是我將如何解決它。另外zip是一個python內建函數,可能最好不要重新定義它。

def alphaToNumber(s): 
    r = 0 
    for x in s: 
     r *= 26 
     r += ord(x) - 96 
    return r 

def numberToAlpha(n, result): 
    head = (n - 1) // 26 
    tail = chr((n - 1) % 26 + 97) 
    if head == 0: 
     return tail + result 
    else: 
     return numberToAlpha(head, tail + result) 

def gen(start, end): 
    start_n = alphaToNumber(start) 
    end_n = alphaToNumber(end) 
    return [numberToAlpha(x, "") for x in range(start_n, end_n + 1)] 

print(gen("a", "ad")) 

# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'aa', 'ab', 'ac', 'ad']