首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用foreach从列表中获取值

使用foreach从列表中获取值
EN

Stack Overflow用户
提问于 2013-05-13 21:28:49
回答 3查看 130关注 0票数 0

我试图从一个列表中获得一个值,该列表使用的是:

代码语言:javascript
运行
复制
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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-05-13 21:38:54

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

代码语言:javascript
运行
复制
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.html

不幸的是,else是在if语句之后出现的,因为这可能会让人感到困惑。这个else与那个if无关;它与for循环有关,这就是为什么它缩进它的方式。(我喜欢Python中的内容,当它们在一起时,您会被迫将它们排列起来。)

票数 2
EN

Stack Overflow用户

发布于 2013-05-13 21:37:05

非常重要的是,pots[0]实际上具有您认为的价值。考虑以下代码:

代码语言:javascript
运行
复制
>>> pots = [[4, 6, 2, 1, 8, 9]]
>>> TherePotValue = 0
>>> for Therepot, member in enumerate(pots[0]):
        TherePotValue = Therepot
        print "(",Therepot,")", member

这就产生了:

代码语言:javascript
运行
复制
( 0 ) 4
( 1 ) 6
( 2 ) 2
( 3 ) 1
( 4 ) 8
( 5 ) 9
>>> print TherePotValue
5
>>> 

如果您看到的是0,我只能假设pots[0]只有一个元素。

票数 1
EN

Stack Overflow用户

发布于 2013-05-13 21:34:24

您的代码等效于:

代码语言:javascript
运行
复制
    TherePotValue = len(pots[0]) - 1

因此,除了在上一次迭代时所做的工作之外,您没有对循环做任何事情。总是得到0表示pos的长度为1。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16531456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档