Python:将单词转换为字母列表,然后根据小写字母返回字母索引

Python:将单词转换为字母列表,然后根据小写字母返回字母索引,python,string,list,Python,String,List,我已经完成了这项任务,但它的最基本形式是寻求帮助缩短它,因此它可以应用于任何单词,而不仅仅是一个有八个字母的单词,以下是我到目前为止得到的(它的功能有点长): 您可能正在寻找的是一个for循环 使用for循环,代码可能如下所示: word = "computer" for letter in word: index = ord(letter)-97 if (index<0) or (index>25): print ("'{}' is not in the lowe

我已经完成了这项任务,但它的最基本形式是寻求帮助缩短它,因此它可以应用于任何单词,而不仅仅是一个有八个字母的单词,以下是我到目前为止得到的(它的功能有点长):


您可能正在寻找的是一个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
下面的代码将针对单词中的每个字母执行(例如,如果单词是列表,则为单词中的元素)

了解有关循环的更多信息的良好开端如下:


您可以在internet上找到大量关于此主题的资源。

您可能正在寻找的是一个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
下面的代码将针对单词中的每个字母执行(例如,如果单词是列表,则为单词中的元素)

了解有关循环的更多信息的良好开端如下:

您可以在internet上找到大量关于此主题的资源。

使用for循环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
用于循环对循环

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

从将每个字母映射到其数字的
dict
开始

import string
d = dict((c, ord(c)-ord('a')) for c in string.lowercase)
然后将字符串中的每个字母配对到适当的索引

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

从将每个字母映射到其数字的
dict
开始

import string
d = dict((c, ord(c)-ord('a')) for c in string.lowercase)
然后将字符串中的每个字母配对到适当的索引

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

感谢您的帮助,我自己用一个函数和一个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
alpha=map(chr,范围(97123))
word=“计算机”
计数=0
y=0
def索引器(编号):
o=字[数]
i=str(α指数(o))
打印(o+“=”+i)
当count
感谢您的帮助,我自己用一个函数和一个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
alpha=map(chr,范围(97123))
word=“计算机”
计数=0
y=0
def索引器(编号):
o=字[数]
i=str(α指数(o))
打印(o+“=”+i)
当count
查找每个字符的字母索引
a->0,b->1,c->2,…z->25
。使用
查找word中的字母:
(或
查找word中的字母列表
)查找每个字符的字母索引
a->0,b->1,c->2,…z->25
。使用
查找word中的字母:
(或单词列表中字母的