如何在Python中迭代字母表

时间:2017-08-23 07:13:59

标签: python list loops xlrd pyexcel

假设a = 0,b = 1 ....,z = 25,aa = 26,......等等。

如何在python中形成一个列表,找到任何给定字母表的索引,假设是ey?

book = xlrd.open_workbook(input("Enter name of the excel file "))
table_list=list(book.sheet_names())
print("the sheets in the excel file are :")
for name in table_list:
     print(name)
first_sheet = book.sheet_by_index(table_list.index(input("Enter sheet name ")))

arrayofvalues = first_sheet.col_values(152,2,239)

我需要在col_val函数中使用获得的值。

还有其他方法吗?

1 个答案:

答案 0 :(得分:3)

这是一个基数为26的转换,只有一点扭曲(a仅在最右边的地方作为零):

def col2idx(colname):
    colname = colname.lower()
    idx = 0
    for digit in colname:
        idx *= 26
        idx += ord(digit) - ord('a') + 1
    return idx - 1


print(col2idx('a'))  # == 0
print(col2idx('b'))  # == 1
print(col2idx('c'))  # == 2
print(col2idx('z'))  # == 25
print(col2idx('aa'))  # == 26
print(col2idx('ab'))  # == 27
print(col2idx('az'))  # == 51
print(col2idx('aij'))  # == 919
print(col2idx('amj'))  # == 1023
print(col2idx('zzad'))  # == 474581