Tho*_*mas 5 python reference list
我正在改编Codecademy的pyglatin.py来制作一个接受和翻译多个单词的翻译器.但是,我在翻译多个单词时遇到了麻烦.我已经能够将原始输入转移到列表并翻译第一个,但我不知道如何引用列表中的下一个项目.任何帮助将不胜感激.
def piglatin1():
pig = 'ay'
original = raw_input('Enter a phrase:').split(' ')
L = list(original)
print L
i = iter(L)
item = i.next()
for item in L:
if len(item) > 0 and item.isalpha():
word = item.lower()
first = word
if first == "a" or first == "e" or first == "i" or first == "o" or first =="u":
new_word = word + pig
print new_word
else:
new_word = word[1:] + word[0:1] + pig
# first word translated
L = []
M = L[:]
L.append(new_word)
print L # secondary list created.
again = raw_input('Translate again? Y/N')
print again
if len(again) > 0 and again.isalpha():
second_word = again.lower()
if second_word == "y":
return piglatin()
else:
print "Okay Dokey!"
else:
print 'Letters only please!'
return piglatin1()
Run Code Online (Sandbox Code Playgroud)
小智 6
我最近也在研究这个问题,并提出了以下解决方案(而不是使用范围,使用枚举来获取索引)。
for index, item in enumerate(L):
next = index + 1
if next < len(L):
print index, item, next
Run Code Online (Sandbox Code Playgroud)
此示例显示如何访问当前索引、当前项,然后访问列表中的下一项(如果它存在于列表的边界中)。
以下是一些可能有帮助的注意事项。
i = iter(L)和 item = i.next()是不必要的。它们在此方法中没有效果,因为您item在该行之后立即重新定义for item in L重新定义。继续注释掉这两行,看看它是否会对您的输出进行任何更改。for item in L将遍历列表中的每个项目。无论您在此循环中编写什么代码,都将为列表中的每个项目执行一次。变量item是迭代的列表元素的句柄。for i in range(0,len(L)). 然后L[i]将是当前项目,L[i+1]您将给出后续项目。