python数字形式转换_在Python中将字母转换为数字
在Python中將字母轉換為數字
如何完成以下步驟?
characters = ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''t''u''v''w''x''y''z']
numbers = ['1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24']
text = raw_input(' Write text: ')
我已經嘗試了許多方法來解決它,但無法做到。 我想做事。 如果我鍵入“ hello”,則輸出的數字將按字母順序排列。 示例a = 1 <字母。
altin asked 2020-02-06T03:46:14Z
14個解決方案
77 votes
那么這樣的事情呢:
print [ord(char) - 96 for char in raw_input('Write Text: ').lower()]
奧德
清單理解
ASCII字符代碼
編輯
自從你問我要解釋后,我會...盡管[?]已經在評論中很好地解釋了它。
讓我們從不止一行開始。
input = raw_input('Write Text: ')
input = input.lower()
output = []
for character in input:
number = ord(character) - 96
output.append(number)
print output
這做同樣的事情,但更具可讀性。 在嘗試理解我的第一個答案之前,請確保您了解這里發生的情況。 這里的一切都是非常標準的,簡單的Python。 要注意的一件事是ord函數。 ord代表序數,幾乎每種高級語言都將提供此類功能。 它為您映射到任何字符的數字表示形式。 ord的逆函數稱為chr。
chr(ord('x')) == 'x' # for any character, not just x.
如果您自己進行測試,則a的序數為97(我上面發布的第三個鏈接將顯示完整的ASCII字符集。)每個小寫字母的范圍為97-122(26個字符)。因此,如果您減去 從任何小寫字母的序號96開始,假設您采用'a'== 1,您將獲得其在字母表中的位置。因此,'b'== 98,'c'== 99等的序數。當您 減去96,'b'== 2,'c'== 3,依此類推。
我發布的初始解決方案的其余部分只是一些Python技巧,您可以學習這些技巧,稱為列表理解。 但是,我不會像在奧爾德是你的朋友的情況下那樣專注于學習以任何語言來解決問題。 我希望這有幫助。
sberry answered 2020-02-06T03:47:04Z
15 votes
您可以使用chr()和ord()在字母和整數之間進行轉換。
這是一個簡單的例子。
>>> chr(97)
'a'
>>> ord('a')
97
Statham answered 2020-02-06T03:47:29Z
9 votes
如果要大量使用此轉換,請考慮計算一次并將結果放入字典中:
>>> import string
>>> di=dict(zip(string.letters,[ord(c)%32 for c in string.letters]))
>>> di['c']
3
優點是字典查找非???#xff0c;而在每次調用時都遍歷列表。
>>> for c in sorted(di.keys()):
>>> print "{0}:{1} ".format(c, di[c])
# what you would expect....
the wolf answered 2020-02-06T03:47:53Z
8 votes
不必太基礎,但這是:
>>> char1 = ['a''b''c''d''e''f''g''h''i''j''k''l'
'm''n''o''p''q''r''s''t''u''v''w''x''y''z']
與此非常不同:
>>> char2 = ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z']
第一個沒有逗號和問題的內容是一個包含26個元素的字符串的一個元素列表。 第二個是26個元素列表,每個列表的長度為單個字符。
如果打印每個:
>>> print char1, len(char1), len(char1[0])
['abcdefghijklmnopqrstuvwxyz'] 1 26
>>> print char2, len(char2), len(char2[0])
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q','r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 26 1
顯然,需要采取額外的步驟才能將characters=['a''b''c'...]的各個字符變成可迭代的字符。
如果您具有從“ a”到“ z”和/或從“ A”到“ Z”的字符序列,則可以通過列表理解輕松返回該字符的編號:
>>> [ord(x)%32 for x in char2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
對于您擁有的數據結構類型,您需要首先訪問該字符串:
>>> [ord(x)%32 for x in char1[0]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
因此,如果您的代碼清單與您的問題相同,則可能是您的問題。
合理的替代方法是:characters=['a''b''c'...]
您可以看到您的characters=['a''b''c'...](不帶逗號)與在像['abc...']這樣的列表中鍵入字符串中的所有字符一樣。
所以現在嘗試:
>>> import string
>>> [ord(x.lower())-96 for x in string.letters]
[1,2,...26, 1,2,3...26] # my ellipses
>>> char3=[string.letters] # one string as element[0]
>>> [ord(x)%32 for x in char3[0]]
>>> [ord(x)%32 for x in [string.letters][0]]
dawg answered 2020-02-06T03:48:58Z
6 votes
這是我以前用于此目的的功能。 適用于大寫和小寫。
def convert_char(old):
if len(old) != 1:
return 0
new = ord(old)
if 65 <= new <= 90:
# Upper case letter
return new - 64
elif 97 <= new <= 122:
# Lower case letter
return new - 96
# Unrecognized character
return 0
parent5446 answered 2020-02-06T03:49:18Z
5 votes
像這樣
[str(ord(c)&31) for c in text]
Kabie answered 2020-02-06T03:49:38Z
3 votes
>>> [str(ord(string.lower(c)) - ord('a') + 1) for c in string.letters]
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17',
'18', '19', '20', '21', '22', '23', '24', '25', '26', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24',
'25', '26']
marcog answered 2020-02-06T03:49:54Z
3 votes
def letter_to_int(letter):
alphabet = list('abcdefghijklmnopqrstuvwxyz')
return alphabet.index(letter) + 1
在此,如果列表包含x,則索引(x)函數將返回x的位置值。
ehfgk78 answered 2020-02-06T03:50:14Z
2 votes
這是我用來將excel列字母轉換為數字的方法(因此限制為3個字母,但是如果您需要更多,可以很容易地擴展它)。 可能不是最好的方法,但是它可以滿足我的需求。
def letter_to_number(letters):
letters = letters.lower()
dictionary = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
strlen = len(letters)
if strlen == 1:
number = dictionary[letters]
elif strlen == 2:
first_letter = letters[0]
first_number = dictionary[first_letter]
second_letter = letters[1]
second_number = dictionary[second_letter]
number = (first_number * 26) + second_number
elif strlen == 3:
first_letter = letters[0]
first_number = dictionary[first_letter]
second_letter = letters[1]
second_number = dictionary[second_letter]
third_letter = letters[2]
third_number = dictionary[third_letter]
number = (first_number * 26 * 26) + (second_number * 26) + third_number
return number
Kurt Maupin answered 2020-02-06T03:50:34Z
1 votes
如果目標是僅轉換字母abcd .... xyz和ABCD .... XYZ,我將使用一個函數:
from string import letters
def rank(x, d = dict((letr,n%26+1) for n,letr in enumerate(letters[0:52]))):
return d[x]
我寫了[0:52]是因為我的Python 2.7版本顯示了該值
* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
用于string.letters參數。
因為參數d接收一個值作為默認參數,所以在執行函數定義以生成函數對象的那一刻,該值的演算僅執行一次。因此,即使該函數被調用了三千次,也可以在不重新計算該值的情況下使用該函數。
順便說一下,該函數的每次調用都不再使用lower()。 在構造默認參數時已處理了大寫字母的情況。
。
一個使用示例:
word = 'supercalifragilisticexpialidocious'
print ''.join( letter if rank(letter)%3!=0 else '.' for letter in word)
結果:
s.pe..a .... ag ... st..e.p.a.d ..... s
。
它也可以與map()一起使用:
print map(rank,'ImmunoElectroPhoresis')
結果:
[9、13、13、21、14、15、5、12、5、3、20、18、15、16、8、15、18、5、19、9、19]
eyquem answered 2020-02-06T03:51:52Z
1 votes
如果您只是想將數字映射到字母,則只需執行以下簡單操作:
def letter_to_index(letter):
_alphabet = 'abcdefghijklmnopqrstuvwxyz'
return next((i for i, _letter in enumerate(_alphabet) if _letter == letter), None)
當然,如果要使其從1開始,則只需添加(i + 1代表i,...等。
regularex answered 2020-02-06T03:52:17Z
1 votes
如果您正相反,例如1 = A,2 = B等,則可以使用以下代碼。 請注意,由于我只能將一個班級的班級轉換為A,B,C等,所以我最多只能升至2級。
loopvariable = 0
numberofdivisions = 53
while (loopvariable
if(loopvariable<26):
print(chr(65+loopvariable))
loopvariable +=1
if(loopvariable > 26 and loopvariable <53):
print(chr(65)+chr(65+(loopvariable-27)))
Haris Np answered 2020-02-06T03:52:37Z
1 votes
使用此功能。 它將字母字符串轉換為其等效的數字值:
def convAlph2Num(sent):
alphArray = list(string.ascii_lowercase)
alphSet = set(alphArray)
sentArray = list(sent.lower())
x = []
for u in sentArray:
if u in alphSet:
u = alphArray.index(u) + 1
x.append(u)
print(x)
return
dabire answered 2020-02-06T03:52:57Z
0 votes
這是我要解決的問題的解決方案,其中您要轉換字符串中所有字母的位置,并以字母的位置返回英文字母的位置。
[https://gist.github.com/bondnotanymore/e0f1dcaacfb782348e74fac8b224769e]
如果您想詳細了解它,請告訴我。我使用了以下概念? -列表理解? -字典理解
nomoreabond2017 answered 2020-02-06T03:53:27Z
總結
以上是生活随笔為你收集整理的python数字形式转换_在Python中将字母转换为数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux 两台服务器之间传输文件和文件
- 下一篇: Python操作文件,报FileNotF