将excel或电子表格列的字母转换为Pythonic方式的编号 [英] Convert an excel or spreadsheet column letter to its number in Pythonic fashion

查看:191
本文介绍了将excel或电子表格列的字母转换为Pythonic方式的编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



工作代码最多两个字母:

  def column_to_number(c):
返回与excel样式列对应的数字。
number = -25
C中的l
如果不是l在string.ascii_letters中:
return False
number + = ord(l.upper()) -64 + 25
返回号码

代码运行:

 >>> column_to_number('2')
False
>>> column_to_number('A')
1
>>> column_to_number('AB')
28

三个字母不起作用

 >>> column_to_number('ABA')
54
>>> column_to_number('AAB')
54

参考: C#中回答的问题

解决方案

有一种方法可以使它更加pythonic(使用三个或更多的字母,使用较少的魔术数字):

  def col2num(col):
num = 0
for c in col:
if c in string.ascii_letters:
num = num * 26 +(ord(c.upper()) - ord('A'))+ 1
return num

作为一个单行使用reduce(不检查输入,可读性较差,所以我不推荐它):

  col2num = lambda col:reduce(lambda x,y:x * 26 + y,[ord(c.upper()) -  ord('A')+ 1 c in col])


Is there a more pythonic way of converting excel-style columns to numbers (starting with 1)?

Working code up to two letters:

def column_to_number(c):
    """Return number corresponding to excel-style column."""
    number=-25
    for l in c:
        if not l in string.ascii_letters:
            return False
        number+=ord(l.upper())-64+25
    return number

Code runs:

>>> column_to_number('2')
False
>>> column_to_number('A')
1
>>> column_to_number('AB')
28

Three letters not working.

>>> column_to_number('ABA')
54
>>> column_to_number('AAB')
54

Reference: question answered in C#

解决方案

There is a way to make it more pythonic (works with three or more letters and uses less magic numbers):

def col2num(col):
    num = 0
    for c in col:
        if c in string.ascii_letters:
            num = num * 26 + (ord(c.upper()) - ord('A')) + 1
    return num

And as a one-liner using reduce (does not check input and is less readable so I don't recommend it):

col2num = lambda col: reduce(lambda x, y: x*26 + y, [ord(c.upper()) - ord('A') + 1 for c in col])

这篇关于将excel或电子表格列的字母转换为Pythonic方式的编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆