Unpack 1 variable, rest to a list

回眸只為那壹抹淺笑 提交于 2021-02-16 06:04:33

问题


I was wondering if this was possible:

def someFunction():
    return list(range(5))
first, rest = someFunction()

print(first) # 0
print(rest) # [1,2,3,4]

I know it could be accomplished with these 3 lines:

result = someFunction()
first = result[0]
rest = result[1:]

回答1:


If you are using Python 3.x, it is possible to do this

first, *rest = someFunction()
print (first, rest)

Read more about it in this PEP

In Python 2, the best you can do is

result = someFunction()
first, rest = result[0], result[1:]


来源:https://stackoverflow.com/questions/21354645/unpack-1-variable-rest-to-a-list

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