参考列表中的下一项:python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19460339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:48:18  来源:igfitidea点击:

Reference next item in list: python

pythonlistreference

提问by Thomas

I'm making a variation of Codecademy's pyglatin.py to make a translator that accepts and translates multiple words. However, I'm having trouble translating more than one word. I've been able to transfer the raw input into a list and translate the first, but I do not know how to reference the next item in the list. Any help would be greatly appreciated.

我正在制作 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()

采纳答案by pravnar

Here are a few things to note that might help.

这里有一些注意事项可能会有所帮助。

  1. The lines i = iter(L)and item = i.next()are unnecessary. They have no effect in this method because you are redefining itemimmediately afterwards in the line for item in L. Go ahead and comment out those two lines to see if it makes any changes in your output.
  2. The looping construct for item in Lwill go once over every item in the list. Whatever code you write within this loop will be executed once for each item in the list. The variable itemis your handle to the list element of an iteration.
  3. If, during any iteration, you really do want to access the "next" element in the list as well, then consider using a looping construct such as for i in range(0,len(L)). Then L[i]will be the current item and L[i+1]will you give the subsequent item.
  1. 线i = iter(L)item = i.next()是不必要的。它们在此方法中不起作用,因为您item随后立即在行中重新定义for item in L。继续注释掉这两行,看看它是否对您的输出进行了任何更改。
  2. 循环结构for item in L将遍历列表中的每个项目。您在此循环中编写的任何代码都将针对列表中的每个项目执行一次。变量item是迭代列表元素的句柄。
  3. 如果在任何迭代过程中,您确实还想访问列表中的“下一个”元素,那么请考虑使用循环结构,例如for i in range(0,len(L)). 然后L[i]将是当前项目,L[i+1]您将提供后续项目。

回答by Nadia

Step by step:

一步步:

  1. If you set variable original in this way:

    original = raw_input('Enter a phrase:').split()
    

    it will be already a list, so need to additional assignment.

  2. What is the purpose of these lines?

    i = iter(L)
    item = i.next()
    
  3. In a loop, you assign variable to the word, when it is actually only the first letter of the word, so it'll be better like this: first = word[0]

  4. Then if you want to check if first is a vowel, you can just do:

    if first in 'aeuoiy'
    
  5. Answer to your actual question: do not assign L to an empty list!

  6. If you want to repeat the action of a function, you can just call it again, no need to rewrite the code.

  1. 如果您以这种方式设置变量 original:

    original = raw_input('Enter a phrase:').split()
    

    它已经是一个列表,所以需要额外的分配。

  2. 这些线的目的是什么?

    i = iter(L)
    item = i.next()
    
  3. 在循环中,您将变量分配给单词,当它实际上只是单词的第一个字母时,这样会更好: first = word[0]

  4. 然后如果你想检查 first 是否是元音,你可以这样做:

    if first in 'aeuoiy'
    
  5. 回答您的实际问题:不要将 L 分配给空列表!

  6. 如果你想重复一个函数的动作,你可以再次调用它,不需要重写代码。

回答by RMcG

There are some slight issues with the code but I think there is one main reason why it will not repeat.

代码有一些小问题,但我认为它不会重复的主要原因之一。

In order to process the entire string the

为了处理整个字符串

again = raw_input('Translate again? Y/N')

and it's succeeding lines should be brought outside the for statement. Also you appear to be setting L to an empty string inside the loop:

并且它的后续行应该放在 for 语句之外。此外,您似乎将 L 设置为循环内的空字符串:

L = []

The following is a modified version of your code which will loop through the entire sentence and then ask for another one.

以下是您的代码的修改版本,它将循环遍历整个句子,然后再请求另一个。

def piglatin():
    pig = 'ay'
    while True:
        L = raw_input('Enter a phrase:').split(' ')
        M = []
        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
                    M.append(new_word)
            else:
                print 'Letters only please!'

        print M # 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 == "n":
           print "Okay Dokey!"
           break

Changes made:

所做的更改:

  • You don't need to cast the return of the split to a list. The split return type is a list.
  • It isn't necessary to make an iterator, the for loop will do this for you.
  • I removed the function as the return type. I'm assuming you were attempting some form of recursion but it isn't strictly necessary.
  • 您不需要将拆分的返回转换为列表。拆分返回类型是一个列表。
  • 没有必要制作迭代器,for 循环会为你做这件事。
  • 我删除了该函数作为返回类型。我假设您正在尝试某种形式的递归,但这并不是绝对必要的。

Hope this helps.

希望这可以帮助。

回答by acknapp

I was working on this problem recently as well and came up with the following solution (rather than use range, use enumerateto get the index).

我最近也在研究这个问题,并提出了以下解决方案(而不是使用范围,使用枚举来获取索引)。

for index, item in enumerate(L):
    next = index + 1
    if next < len(L):
        print index, item, next

This example shows how to access the current index, the current item, and then the next item in the list (if it exists in the bounds of the list).

此示例显示如何访问当前索引、当前项,然后访问列表中的下一项(如果它存在于列表的边界中)。