3 回答

TA貢獻1876條經驗 獲得超5個贊
with open('alpha.txt') as f:
lines = list(enumerate((line for line in (l.strip() for l in f) if line),start = 1)) # also skip empty lines
for item in lines:
print ("{}={}".format(item[1],item[0]))
輸出:
a=1
b=2
c=3
或者:
with open('alpha.txt') as f:
for line in enumerate(f,start = 1):
print("{}={}".format(line[1][0], line[0]))
輸出:
a=1
b=2
c=3
或者
with open('test.txt') as f:
for idx, line in enumerate(f,start = 1):
print('{}={}'.format(line[0], idx))
輸出:
a=1
b=2
c=3

TA貢獻2051條經驗 獲得超10個贊
您可以通過調用ord()字符將字母轉換為其數值。
ord('a')將等于 97。如果你想偏移你的字符從 1 開始,你可以減去 96,或者你可以使用類似的東西offset = ord('a')-1來讓它更有活力。
import string # dont need to import for your version
letters = string.ascii_letters[:26] # lowercase letters for testing
offset = ord('a') - 1
for letter in letters:
輸出:
a = 1
b = 2
c = 3
d = 4
等等。
編輯:我的解決方案與其他解決方案的不同之處在于我實際上是將每個字母轉換為其值。如果您只想在解決方案出現時對其進行編號,那么我的解決方案將是錯誤的。
例如,如果給定
letters = ['b', 'c', 'a']
我的解決方案將輸出
b = 2
c = 3
a = 1
其他發布的解決方案仍將編號字母
b = 1
c = 2
a = 3

TA貢獻1946條經驗 獲得超4個贊
你也可以使用stringlib:
[print(c, '=', i+1) for i, c in enumerate(string.ascii_lowercase)]
輸出:
a = 1
b = 2
c = 3
d = 4
e = 5
等等。
添加回答
舉報