【问题标题】:How can I access lists that are generated within a function?如何访问在函数中生成的列表?
【发布时间】:2020-08-01 21:33:58
【问题描述】:

所以我对一些 python 作业有点坚持......这是我的第一个问题,顺便说一句,如果格式错误,我很抱歉。

有一个函数“co-ordinates_generator()”可以产生一个坐标列表,[[x, y], [x, y], [x, y]] 等等。

我必须创建一个函数,利用这些坐标并使用这些坐标将图钉相应地打印到地图上。 我想我可以通过这样做来实现:

def place_coords():
     for point in co-ordinates_generator():
           if point[0] == '1': 
                place_pin() etc. etc....        

这确实有效,但是当我这样做时,“co_ordinates_generator()”生成的列表会生成两次。换句话说,我的屏幕上打印了两个列表,而不是我应该使用的一个列表。

我唯一的假设是因为在部分:

for point in co-ordiantes_generator():

我调用 co-ordinates_generator() 并且这样做会触发该函数,导致它打印,然后在我调用 place_coords() 时再次打印。这是正确的

如果是这样,或者其他情况,我将如何解决这个问题?我已经尝试完全删除“for _ in ____”部分,但这会产生各种麻烦,例如“'pin' is not defined”。还有一个事实是,我已经基于使用“for _ in ___”部分编写了一大堆 for-each 循环。

抱歉,篇幅较长!并提前感谢您。

【问题讨论】:

  • 请显示co-ordinates_generator()的函数声明。

标签: python list function foreach


【解决方案1】:

如果没有你的函数,我猜你没有从函数返回任何值。

def co-ordinates_generator():
    ....   # your existing code
    ....   # your existing code
    ....    # your existing code
    return co-ordiantes_variable # whatever name you have defined for the desired result.

result = co-ordinates_generator()
for point in result:
    ....   # your existing code
    ....   # your existing code
    ....   # your existing code

【讨论】:

    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 2010-12-25
    • 2014-09-09
    • 2021-09-07
    • 2010-09-10
    相关资源
    最近更新 更多