Expand tuple into arguments while casting them? [duplicate]

六月ゝ 毕业季﹏ 提交于 2021-02-08 08:22:22

问题


I have this:

blah = random.randint(int(minmax[0]), int(minmax[1]))

I know this is possible:

minimum, maximum = int(minmax[0]), int(minmax[1])
blah = random.randint(minimum, maximum)

Can I do this second one in a single line using tuple-argument expansion? For example, if minmax was a tuple of integers to begin with, I could do:

blah = random.randint(*minmax)

But I don't have a tuple of ints, I have a tuple of strs. Obviously it's not a big deal one way or the other. I'm just curious.


回答1:


Yeah, that's doable:

blah = random.randint(*map(int, minmax))

Use map(int, ...) to perform the type conversion.




回答2:


You may use a list comprehension expression to type-cast the elements to int and then unpack the list as:

random.randint(*[int(i) for i in minmax])
#              ^    ^ type-cast minmax elements to `int`
#              ^ unpack the `list`   


来源:https://stackoverflow.com/questions/42011757/expand-tuple-into-arguments-while-casting-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!