【问题标题】:How to Iterate over Alphabets in Python如何在 Python 中迭代字母表
【发布时间】:2017-08-23 07:13:59
【问题描述】:

让我们假设 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函数中使用得到的值。

还有其他方法吗?

【问题讨论】:

  • 从字母迭代到 Excel 表格操作,您真正想做的是什么?
  • 最好是做一些数学运算,然后提出一个计算索引的函数,而不是用list 所有这些我>

标签: python list loops xlrd pyexcel


【解决方案1】:

这是一个以 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

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 2022-12-16
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2012-05-05
    • 1970-01-01
    相关资源
    最近更新 更多