我试图从一个列表中获得一个值,该列表使用的是:
for Therepot, member in enumerate(pots[0]):
TherePotValue = Therepot
罐子里装着4,6,2,1,8,9之类的东西
编辑
要返回值,我应该将变量TherePotValue指向成员,而不是TherePot,它是索引。
运行测试:
TherePot =0,成员=4
TherePot =1,成员=6
TherePot =2,成员=2
TherePot =3,成员=1
TherePot =4,成员=8
TherePot =5,成员=9
发布于 2013-05-13 21:38:54
我认为这些例子会帮助你做你想做的事:
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
编辑:这些评论让我意识到,for
循环中的for
可能会让我感到困惑。
在Python中,for
循环可以有自己的else
情况。Raymond评论说,他希望关键字是类似when_no_break
的,因为您使用此else
的唯一一次是使用break
关键字!
如果for
循环使用break
提前退出,则else
代码不会运行。但是,如果for
循环一直运行到最后,并且从来没有发生过break
,那么在最后运行else
代码。Nick称这是一个“完成子句”,以将其与if
语句中的“条件else”区别开来。
不幸的是,else
是在if
语句之后出现的,因为这可能会让人感到困惑。这个else
与那个if
无关;它与for
循环有关,这就是为什么它缩进它的方式。(我喜欢Python中的内容,当它们在一起时,您会被迫将它们排列起来。)
发布于 2013-05-13 21:37:05
非常重要的是,pots[0]
实际上具有您认为的价值。考虑以下代码:
>>> pots = [[4, 6, 2, 1, 8, 9]]
>>> TherePotValue = 0
>>> for Therepot, member in enumerate(pots[0]):
TherePotValue = Therepot
print "(",Therepot,")", member
这就产生了:
( 0 ) 4
( 1 ) 6
( 2 ) 2
( 3 ) 1
( 4 ) 8
( 5 ) 9
>>> print TherePotValue
5
>>>
如果您看到的是0
,我只能假设pots[0]
只有一个元素。
发布于 2013-05-13 21:34:24
您的代码等效于:
TherePotValue = len(pots[0]) - 1
因此,除了在上一次迭代时所做的工作之外,您没有对循环做任何事情。总是得到0表示pos的长度为1。
https://stackoverflow.com/questions/16531456
复制相似问题