使用foreach从列表中获取价值

时间:2013-05-13 21:28:50

标签: python foreach

我试图从列表中获取每个值的值:

for Therepot, member in enumerate(pots[0]):
        TherePotValue = Therepot

pot [0]拥有类似[4,6,2,1,8,9]

的东西

修改


要返回值,我应该将我的变量TherePotValue指向成员,而不是TherePot女巫是索引。

运行测试:

TherePot = 0,Member = 4

TherePot = 1,成员= 6

TherePot = 2,会员= 2

TherePot = 3,会员= 1

TherePot = 4,会员= 8

TherePot = 5,Member = 9

3 个答案:

答案 0 :(得分:2)

我认为这些例子可以帮助您做您想做的事情:

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

编辑:评论让我意识到else循环中的for可能会令人困惑。

在Python中,for循环可以有自己的else个案例。 Raymond Hettinger评论说他希望关键字类似于when_no_break,因为您使用此else的唯一时间是使用break关键字!

如果for循环提前退出,使用break,则else代码不会运行。但是如果for循环一直运行到最后并且没有break发生,那么最后else代码就会运行。 Nick Coghlan称这是一个“完成条款”,以区别于if语句中的“条件别”。

https://ncoghlan_devs-python-notes.readthedocs.org/en/latest/python_concepts/break_else.html

有点不幸的是elseif声明之后发生,因为这可能令人困惑。那elseif无关;它与for循环一致,这就是为什么它缩进它的方式。 (我在Python中喜欢这样,当你们一起去时,你们不得不排队。)

答案 1 :(得分:1)

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]只有一个元素。

答案 2 :(得分:0)

您的代码相当于:

    TherePotValue = len(pots[0]) - 1

所以除了你在上一次迭代中所做的事情之外,你没有对循环做任何事情。始终为0表示pos [0]的长度为1。