我已经完成了任务,但是以最基本的形式寻找帮助缩短它,所以它可以应用于任何一个字,而不仅仅是一个八字母,这是我到目前为止所做的事情(有点长):
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 :(得分:2)
您可能正在寻找的是 for-loop 。
使用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
对于单词中的每个字母(或单词中的单词,如果单词是列表),将执行以下代码。
开始了解有关循环的更多信息,请访问:https://en.wikibooks.org/wiki/Python_Programming/Loops
您可以在互联网上找到大量涉及此主题的资源。
答案 1 :(得分: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
答案 2 :(得分:0)
从dict
开始,将每个字母映射到其编号。
import string
d = dict((c, ord(c)-ord('a')) for c in string.lowercase)
然后将字符串的每个字母与相应的索引配对。
result = [(c, d[c]) for c in word]
答案 3 :(得分: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