实现说明
itertools.starmap 解包参数元组可以归结为函数 power、main、arguments。
使用要点
- 跑完文件,输出里会留下标记——
powers:、labels:、joined:。 - 执行文件,
main会按顺序走完arguments。
常见问题
运行「itertools.starmap 解包参数元组」会打印什么?
运行文件本身,powers:、labels:、joined: 这些前缀各对应一段演示逻辑。
签名一览:def power(base: int, exponent: int) -> int
核心语句
def power(base: int, exponent: int) -> int:
return base ** exponent
def arguments():
yield ("x", "y")
yield ("z", "w")
代码示例
from itertools import starmap
def power(base: int, exponent: int) -> int:
return base ** exponent
def main() -> None:
pairs = [(2, 3), (4, 5), (6, 7)]
print("powers:", list(starmap(power, pairs)))
# starmap unpacks each tuple into positional arguments.
rows = [("alpha", 3), ("beta", 1), ("gamma", 2)]
labels = starmap(lambda name, count: name * count, rows)
print("labels:", list(labels))
# The input can be lazy; starmap consumes it on demand.
def arguments():
yield ("x", "y")
yield ("z", "w")
joined = starmap(lambda left, right: left + "-" + right, arguments())
print("joined:", list(joined))
print("empty:", list(starmap(power, [])))
if __name__ == "__main__":
main()