2016-10-01 44 views
0

我已經完成了任務,但是以最基本的形式尋找縮短它的幫助,因此它可以應用於任何單詞而不僅僅是一個單詞有八個字母,這裏就是我有這麼遠(有點長爲它做什麼):Python:將單詞轉換爲字母列表,然後將字母索引與小寫字母對齊

alpha = map(chr, range(97, 123)) 
word = "computer" 
word_list = list(word) 

one = word[0] 
two = word[1] 
three = word[2] 
four = word[3] 
five = word[4] 
six = word[5] 
seven = word[6] 
eight = word[7] 


one_index = str(alpha.index(one)) 
two_index = str(alpha.index(two)) 
three_index = str(alpha.index(three)) 
four_index = str(alpha.index(four)) 
five_index = str(alpha.index(five)) 
six_index = str(alpha.index(six)) 
seven_index = str(alpha.index(seven)) 
eight_index = str(alpha.index(eight)) 

print (one + "=" + one_index) 
print (two + "=" + two_index) 
print (three + "=" + three_index) 
print (four + "=" + four_index) 
print (five + "=" + five_index) 
print (six + "=" + six_index) 
print (seven + "=" + seven_index) 
print (eight + "=" + eight_index) 
+0

它找到字母每個字符的索引a - > 0,b - > 1,c - > 2,... z - > 25'。 –

+0

使用'用於單詞中的字母:'(或'用於word_list中的字母') – furas

回答

2

什麼你可能尋找的是for循環一個

使用一個for循環的代碼看起來是這樣的:

word = "computer" 

for letter in word: 
    index = ord(letter)-97 
    if (index<0) or (index>25): 
    print ("'{}' is not in the lowercase alphabet.".format(letter)) 
    else: 
    print ("{}={}".format(letter, str(index+1))) # +1 to make a=1 

如果使用

for letter in word: 
    #code 

下面的代碼將在單詞的每個字母(或元素在Word中執行如果單詞是一個例子)。

一個良好的開端,以瞭解更多關於循環是在這裏:​​

你可以找到噸在互聯網ressources涉及這一話題。

0

使用for循環迴路,

alpha = map(chr, range(97, 123)) 
word = "computer" 
for l in word: 
    print '{} = {}'.format(l,alpha.index(l.lower())) 

結果

c = 2 
o = 14 
m = 12 
p = 15 
u = 20 
t = 19 
e = 4 
r = 17 
0

開始用dict每個信其號映射。

import string 
d = dict((c, ord(c)-ord('a')) for c in string.lowercase) 

然後將字符串的每個字母與適當的索引配對。

result = [(c, d[c]) for c in word] 
0

感謝幫助管理使用功能和while循環,而不是作爲短期解決它自己以不同的方式,但將所有的小寫的話工作:

alpha = map(chr, range (97,123)) 
word = "computer" 
count = 0 
y = 0 

def indexfinder (number): 
    o = word[number] 
    i = str(alpha.index(o)) 
    print (o + "=" + i) 


while count < len(word): 
    count = count + 1 
    indexfinder (y) 
    y = y+1 
相關問題