lst = pots[0]
# solution using a for loop
for i, member in enumerate(lst):
# i is the position in the list
# member is the data item from the list
assert lst[i] == member # cannot ever fail
if member == the_one_we_want:
break # exit loop, variables i and member are set
else:
# the_one_we_want was never found
i = -1 # signal that we never found it
# solution using .index() method function on a list
try:
i = lst.index(the_one_we_want)
except ValueError:
# the_one_we_want was not found in lst
i = -1 # signal that we never found it
您的代码相当于:
因此,除了在上一次迭代中所做的操作外,您没有对循环执行任何操作。总是得到0表示位置[0]的长度为1。你知道吗
非常重要的是
pots[0]
实际上具有您认为的价值。考虑以下代码:这将产生:
如果你看到
0
,我只能假设pots[0]
只有一个元素。你知道吗我认为这些例子会帮助你做你想做的事情:
编辑:这些评论让我意识到,
for
循环中的else
可能会让人困惑。你知道吗在Python中,
for
循环可以有自己的else
大小写。raymondhettinger评论说,他希望关键字是when_no_break
这样的,因为您唯一使用这个else
的时候是使用break
关键字!你知道吗如果
for
循环提前退出,则break
代码不会运行。但是如果for
循环一直运行到最后,并且没有break
发生,那么在最后else
代码运行。Nick Coghlan称之为“completion子句”,以区别于if
语句中的“conditional else”。你知道吗https://ncoghlan_devs-python-notes.readthedocs.org/en/latest/python_concepts/break_else.html
有点不幸的是,
else
紧跟在if
语句之后,因为这可能会让人困惑。那else
与那if
没有关系;它与for
循环有关,这就是它缩进的原因。(我很喜欢在Python中,当它们一起运行时,您必须将它们排列起来。)相关问题 更多 >
编程相关推荐