我有一個包含字母數字字符的串列,如下所示
l1 = ['G1','L1']
我想知道我們是否有類似下面的東西
for i in range(l1): #this doesn't work because range is only for numeric values
for i in range(G1:L1): #this also doesn't work
但是,我希望i每次運行的值從G1to H1to I1to to to J1toK1變為L1
uj5u.com熱心網友回復:
Range 總是需要一個數字并且不能使用字串。
但是,您可以使用內置ord()函式將字母轉換為數字,然后使用該chr()函式將它們從數字轉換回 ASCII 字符。
代碼
a = [chr(c) '1' for c in range(ord('G'), ord('M'))]
print(a)
輸出
['G1', 'H1', 'I1', 'J1', 'K1', 'L1']
更新:雙字符的解決方案。
為雙字符做這件事有點復雜,但這個StackOverflow 答案有一個解決方案。您可以簡單地使用該答案中的from_excel()andto_excel()函式,并在我的上述代碼中替換它們,如下所示。
代碼
a = [to_excel(i) for i in range(from_excel('G'), from_excel('AG'))]
print(a)
輸出
['G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF']
uj5u.com熱心網友回復:
您可以使用:
from openpyxl.utils import coordinate_to_tuple, get_column_letter
def excel_range(start, end):
t1 = coordinate_to_tuple(start)
t2 = coordinate_to_tuple(end)
rows, cols = zip(t1, t2)
cells = []
for r in range(rows[0], rows[1] 1):
for c in range(cols[0], cols[1] 1):
cells.append(f'{get_column_letter(c)}{r}')
return cells
cells = excel_range('AA1', 'AC4')
輸出:
>>> cells
['AA1',
'AB1',
'AC1',
'AA2',
'AB2',
'AC2',
'AA3',
'AB3',
'AC3',
'AA4',
'AB4',
'AC4']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/448658.html
