【问题标题】:How can I get multiple sets of coordinates as arguments for a function?如何获取多组坐标作为函数的参数?
【发布时间】:2020-02-23 18:29:39
【问题描述】:

我有一个函数,pixel,它在窗口中的某个点绘制一个像素。例如,pixel(10, 10) 将在点 (10, 10) 处绘制一个像素。

在一个新函数pixels 中,我希望它可以通过键入pixels((10, 10), (11, 11), ...) 之类的内容来执行,并且它将使用pixel 函数在列出的坐标处绘制像素所需的次数。

【问题讨论】:

标签: python function arguments


【解决方案1】:
def pixel(x, y):
    print(f"drawing pixel at ({x}, {y})")

def pixels(*args):
    for arg in args:
        assert isinstance(arg, tuple)
        pixel(*arg)

pixels((10, 10), (20, 20), (34, 66))

输出:

drawing pixel at (10, 10)
drawing pixel at (20, 20)
drawing pixel at (34, 66)

在将任何参数传递给pixel 之前,最好断言所有参数都是元组。它需要两个串联的 for 循环,或者使用 all,但至少如果所有参数实际上都是元组,您将只绘制任何像素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 2013-12-29
    • 2018-07-07
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多