简体   繁体   中英

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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