【问题标题】:Understanding the asterisk operator in python when it's before the function in a parenthesis在括号中的函数之前理解python中的星号运算符
【发布时间】:2021-10-01 02:36:49
【问题描述】:

我知道星号用于解压缩系统参数等值或将列表解压缩为变量。

但我之前在这个 asyncio 示例中没有见过这种语法。

我在这里阅读了这篇文章,https://realpython.com/async-io-python/#the-10000-foot-view-of-async-io,但我不明白星号运算符在这种情况下在做什么。

#!/usr/bin/env python3
# rand.py

import asyncio
import random

# ANSI colors
c = (
    "\033[0m",   # End of color
    "\033[36m",  # Cyan
    "\033[91m",  # Red
    "\033[35m",  # Magenta
)

async def makerandom(idx: int, threshold: int = 6) -> int:
    print(c[idx + 1] + f"Initiated makerandom({idx}).")
    i = random.randint(0, 10)
    while i <= threshold:
        print(c[idx + 1] + f"makerandom({idx}) == {i} too low; retrying.")
        await asyncio.sleep(idx + 1)
        i = random.randint(0, 10)
    print(c[idx + 1] + f"---> Finished: makerandom({idx}) == {i}" + c[0])
    return i

async def main():
    res = await asyncio.gather(*(makerandom(i, 10 - i - 1) for i in range(3)))
    return res

if __name__ == "__main__":
    random.seed(444)
    r1, r2, r3 = asyncio.run(main())
    print()
    print(f"r1: {r1}, r2: {r2}, r3: {r3}")

async def main function 下方makerandom 之前有一个星号。有人可以解释它在这种情况下的作用吗?我正在尝试了解 async / await 的工作原理。

我看了这个答案,Python asterisk before function,但它并没有真正解释它。

【问题讨论】:

  • 它的意思和其他地方的意思一样。

标签: python asynchronous syntax python-asyncio argument-unpacking


【解决方案1】:

星号不在makerandom之前,它在生成器表达式之前

(makerandom(i, 10 - i - 1) for i in range(3))

asyncio.gather 不将可迭代对象作为其第一个参数;它接受可变数量的可等待对象作为位置参数。为了从生成器表达式获取到那个,您需要解压缩生成器。

在这种特殊情况下,星号解包

asyncio.gather(*(makerandom(i, 10 - i - 1) for i in range(3)))

进入

asyncio.gather(makerandom(0, 9), makerandom(1, 8), makerandom(2, 7))

【讨论】:

    【解决方案2】:

    星号,表示unpacking。它将iterable 传播成几个arguments,如下所示:

    array = [1, 2, 3]
    print(*array)
    

    将与

    相同
    print(1, 2, 3)
    

    另一个例子:

    generator = (x for x in range(10) if my_function(x))
    print(*generator)
    

    一个星号用于普通的迭代,但是当涉及到mappings时,您也可以使用双星号作为**,以便将映射解压缩为关键字参数,如下所示:

    dictionary = {"hello": 1, "world": 2}
    my_function(**dictionary)
    

    这相当于my_function(hello=1, world=2)。 您也可以使用普通的单星号来仅从映射中解包键:

    print(*{"hello": 1, "world": 2})
    

    这将导致hello world

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 2011-02-24
      相关资源
      最近更新 更多