繁体   English   中英

遍历python列表索引

[英]loop through python list index

我有一个列表,每当我在程序中输入“ 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()
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()

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

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

请注意,此代码最终将超出范围。 如果要环绕,可以在i上执行% len(categories)

大多数时候,即使不是更好,也有可能避免在Python中使用索引。 在您的情况下,一种方法是使用列表中的生成器 当用户输入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 +

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM