par*_*axi 10 python excel python-2.x google-sheets
是否有更多pythonic方式将excel样式列转换为数字(从1开始)?
最多两个字母的工作代码:
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
Run Code Online (Sandbox Code Playgroud)
代码运行:
>>> column_to_number('2')
False
>>> column_to_number('A')
1
>>> column_to_number('AB')
28
Run Code Online (Sandbox Code Playgroud)
三个字母不起作用.
>>> column_to_number('ABA')
54
>>> column_to_number('AAB')
54
Run Code Online (Sandbox Code Playgroud)
参考: C#中回答的问题
Syl*_*ain 26
有一种方法可以使它更加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
Run Code Online (Sandbox Code Playgroud)
并且作为使用reduce的单线程(不检查输入并且不太可读,因此我不推荐它):
col2num = lambda col: reduce(lambda x, y: x*26 + y, [ord(c.upper()) - ord('A') + 1 for c in col])
Run Code Online (Sandbox Code Playgroud)
dev*_*von 10
excel_col_num = lambda a: 0 if a == '' else 1 + ord(a[-1]) - ord('A') + 26 * excel_col_num(a[:-1])
excel_col_name = lambda n: '' if n <= 0 else excel_col_name((n - 1) // 26) + chr((n - 1) % 26 + ord('A'))
Run Code Online (Sandbox Code Playgroud)
def excel_column_name(n):
"""Number to Excel-style column name, e.g., 1 = A, 26 = Z, 27 = AA, 703 = AAA."""
name = ''
while n > 0:
n, r = divmod (n - 1, 26)
name = chr(r + ord('A')) + name
return name
def excel_column_number(name):
"""Excel-style column name to number, e.g., A = 1, Z = 26, AA = 27, AAA = 703."""
n = 0
for c in name:
n = n * 26 + 1 + ord(c) - ord('A')
return n
def test (name, number):
for n in [0, 1, 2, 3, 24, 25, 26, 27, 702, 703, 704, 2708874, 1110829947]:
a = name(n)
n2 = number(a)
a2 = name(n2)
print ("%10d %-9s %s" % (n, a, "ok" if a == a2 and n == n2 else "error %d %s" % (n2, a2)))
test (excel_column_name, excel_column_number)
test (excel_col_name, excel_col_num)
Run Code Online (Sandbox Code Playgroud)
0 ok
1 A ok
2 B ok
3 C ok
24 X ok
25 Y ok
26 Z ok
27 AA ok
702 ZZ ok
703 AAA ok
704 AAB ok
2708874 EXCEL ok
1110829947 COLUMNS ok
Run Code Online (Sandbox Code Playgroud)
这是一种方法.它是XlsxWriter模块中代码的变体:
def col_to_num(col_str):
""" Convert base26 column string to number. """
expn = 0
col_num = 0
for char in reversed(col_str):
col_num += (ord(char) - ord('A') + 1) * (26 ** expn)
expn += 1
return col_num
>>> col_to_num('A')
1
>>> col_to_num('AB')
28
>>> col_to_num('ABA')
729
>>> col_to_num('AAB')
704
Run Code Online (Sandbox Code Playgroud)
小智 6
使用 openpyxl
import openpyxl
(column_string, row) = openpyxl.cell.coordinate_from_string(address)
column = openpyxl.cell.column_index_from_string(column_string)
Run Code Online (Sandbox Code Playgroud)
小智 5
安装 openpyxl 模块后,您可以将以下内容添加到控制台:
>>> from openpyxl.utils import get_column_letter, column_index_from_string
>>> get_column_letter(1)
'A'
>>> column_index_from_string('A')
1
Run Code Online (Sandbox Code Playgroud)
只需更改字母和数字即可满足您的需求。