循环遍历python列表索引
我有一个列表,每次我在程序中输入N时,我都希望列表打印下一个索引的内容循环遍历python列表索引,python,list,for-loop,iteration,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) 我知道上面的代码试图将整数添加到字符串中并抛出错误。我没有弄清楚的是如何增加索引 我已经看了其他一些关于类
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()
此代码将跟踪索引,并在每次使用时递增索引:
i = 0
categories = ["hey", "1", "2" ,"3"]
...
elif item == "N":
print(categories[i])
i += 1
请注意,这段代码最终会越界。如果您想总结一下,您可以在i上使用%lencategories。大多数情况下,如果不是更好的话,也可以避免在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+请注意,缩进在python中非常重要。小心。for循环不正确。而且,你应该解释你想做什么,以便我们建议最好的方法。如果我理解正确,您根本不需要for循环,只需要一个索引。@keyser在这里添加代码是我的错误。代码在程序中正确缩进。@Cs142您需要进一步解释您试图执行的操作,我们无法简单地通过您的代码来理解。每次我输入N时,您的意思是什么?是否有一个外部循环包含一个您没有显示的输入?@PaulLo该程序是一个简单的购物清单。我正在尝试添加类别的计划,将有一个类别列表。默认情况下,当程序启动时,第一个类别将显示为类别[0],然后提示输入项目。当我按下一个按钮时,说N我希望类别更改为打印列表中的下一项,依此类推。我在原来的帖子中添加了示例输出,以澄清问题。这是这里最容易理解的解决方案。它甚至看起来使用len将允许我创建一个嵌套的if语句,表示当len==category[5]。。做事
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!