使用foreach从列表中获取值

2024-05-18 04:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从列表中获取值,使用for each:

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

罐子[0]装着类似于[4,6,2,1,8,9]的东西

编辑


要返回值,我应该将变量TherePotValue指向member,而不是索引的TherePot。你知道吗

运行测试:

报告=0,成员=4

报告=1,成员=6

报告=2,成员=2

报告=3,成员=1

报告=4,成员=8

报告=5,成员=9


Tags: in编辑列表for报告成员member指向
3条回答

您的代码相当于:

    TherePotValue = len(pots[0]) - 1

因此,除了在上一次迭代中所做的操作外,您没有对循环执行任何操作。总是得到0表示位置[0]的长度为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]只有一个元素。你知道吗

我认为这些例子会帮助你做你想做的事情:

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循环中的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中,当它们一起运行时,您必须将它们排列起来。)

相关问题 更多 >