循环遍历python列表索引

时间:2015-02-02 15:01:25

标签: python list for-loop iteration

我有一个列表,每次在程序中输入“N”时,我希望列表打印下一个索引的内容。

categories = ["Produce", "Meat", "Dairy" ,"Misc"]
 ...
elif item == "N":
    for d in categories[:1]:
        d = categories[0]
        d += 1
        print(d)

据我所知,上面的代码试图在字符串中添加一个整数并抛出错误。我无法弄清楚的是如何增加索引。

我已经查看过其他一些有关类似问题的帖子,但解决方案并没有脱离上下文。

示例输出

Add Item to list

Produce
>>Tomatoes
>>Grapes
Meat
>>Hamburger
Dairy
>>

整个计划

def add_item():
    exit_list = ["F", "Finished"]
    lists = []

    start = input("Would you like to add an item to the list? Y/N")
    print("Add Item to list")
    categories = ["Produce", "Meat", "dairy","snacks/boxed goods", "Cans", "Misc"]

    print(categories[0])
    while start in ('y', 'Y'):
        item = input(">>")
        if item in exit_list:
            break
        elif item == "N":
            for d in categories[:1]:
                i = 0
                i +=1
                d = categories[i]
                print(d)

        elif item:
            lists.append(item)
    else:
        print("ok")
    print(lists)
    return lists

add_item()

3 个答案:

答案 0 :(得分:0)

def add_item():
    exit_list = ["F", "Finished"]
    lists = []

    start = input("Would you like to add an item to the list? Y/N")
    print("Add Item to list")
    categories = ["Produce", "Meat", "dairy","snacks/boxed goods", "Cans", "Misc"]

    print(categories[0])
    i=0
    while start in ('y', 'Y'):
        item = input(">>")
        if item in exit_list:
            break
        elif item == "N":
                i +=1
                print(categories[i])

        elif item:
            lists.append(item)
    else:
        print("ok")
    print(lists)
    return lists

add_item()

答案 1 :(得分:0)

此代码将跟踪索引并在每次使用时递增:

i = 0
categories = ["hey", "1", "2" ,"3"] 
...
elif item == "N":
    print(categories[i])
    i += 1

请注意,此代码最终将超出范围。如果你想环绕你可以做,例如% len(categories)上的i

答案 2 :(得分:0)

大多数情况下,如果不是更好的话,可以避免在Python中使用索引。在您的情况下,一种方法是在列表中使用generator。当用户输入q时,以下代码将退出,当用户输入n时打印下一个项目,如果输入是其他内容则不执行任何操作。

categories = ["hey", "1", "2" ,"3"]                                             
user_input = None                                                               

# Transform your list into an iterator                                                                
categories = iter(categories)                                                   

# While the user doesn't want to quit                                                                                    
while user_input != "q":             
    # The user's input is transformed to lower case                                           
    user_input = input("What do you want to do ? ").lower()                     
    if user_input == "n":                                                       
        try:                                       
            # We print the next value on the iterator i.e. the next 
            # value in your list                             
            print(next(categories))                                             
        except StopIteration:                                                   
            # Raised when the iterator reached the end i.e. when we
            # have printed all the values in the list
            print("You've printed all the list!")                                  
            break         

一个可能的输出是:

What do you want to do ? hello # Nothing happens here 
What do you want to do ? n
hey
What do you want to do ? n
1
What do you want to do ? n
2
What do you want to do ? n
3
What do you want to do ? n
You've printed all the list!

请注意,此示例使用的是Python3 +