简体   繁体   English

Python:在单个表达式中使用不同的参数重复函数

[英]Python: repeat function with different arguments in a single expression

I love being able to assign and use multiple variables in a single expression - it looks particularly elegant. 我喜欢能够在一个表达式中分配和使用多个变量 - 它看起来特别优雅。 How can I repeat any arbitrary function and have my code behave as expected without using a loop? 如何在不使用循环的情况下重复任何任意函数并使我的代码按预期运行? To demonstrate the integer conversion below should only use a single line. 要演示下面的整数转换,应该只使用一行。

string = '75 45 120'

v0,v1,v2 = string.split()

v0 = int(v0)
v1 = int(v1)
v2 = int(v2)

print(v0,v1,v2,v1+v2,sep=', ') # 75, 45, 120, 165

Use map : 使用map

v0, v1, v2 = map(int, string.split())

You can use a list comprehension or generator expression if you want, but for things like this, map can be cleaner. 如果需要,您可以使用列表推导或生成器表达式,但对于这样的事情, map可以更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM