1. 程式人生 > >Python-實現Excel表取值列名稱

Python-實現Excel表取值列名稱

給定一個正整數,返回它在excel表中出現的對應列名稱

For example:

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

1:構建數字對應字母的字典,然後進行計算(注意:沒有0對應的字母,有26對應的字母)

def convertToTitle(self, n):

"""

:type n: int

:rtype: str

"""

chaDic = {1:'A', 2:'B', 3:'C', 4:'D', 5:'E', 6:'F', 7:'G', 8:'H', 9:'I', 10:'J', 11:'K'

, 12:'L', 13:'M', 14:'N', 15:'O', 16:'P', 17:'Q', 18:'R', 19:'S', 20:'T', 21:'U'

, 22:'V', 23:'W', 24:'X', 25:'Y', 26:'Z'} #注意,沒有0對應的字母

rStr = ""

while n!=0:

if n<=26: #存在26對應的字母

rStr = chaDic.get(n)+rStr

n = 0

else:

res = n%26

if res == 0: #因為沒有0對應的字母,所以如果餘數為0的話需要自動提出26

res = 26

n -= 26

rStr = chaDic.get(res)+rStr

n = n//26

return rStr

2:利用chr()和ord()方法(參考他人程式碼)

chr() 用一個範圍在 range(256)內的(就是0~255)整數作引數,返回一個對應的字元

ord() 函式是 chr() 函式(對於8位的ASCII字串)或 unichr() 函式(對於Unicode物件)的配對函式,它以一個字元(長度為1的字串)作為引數,返回對應的 ASCII 數值,或者 Unicode 數值,如果所給的 Unicode 字元超出了你的 Python 定義範圍,則會引發一個 TypeError 的異常

def convertToTitle(self, n):

"""

:type n: int

:rtype: str

"""

rStr = ""

while n!=0:

res = n%26

if res == 0:

res =26

n -= 26

rStr = chr(ord('A')+res-1) + rStr

n = n//26

return rStr


​​​​

演算法題來自:https://leetcode-cn.com/problems/excel-sheet-column-title/description/