The only way i could do this was:
var1 = list[0]
var2 = list[1]
var3 = list[2]
var4 = list[3]
...
Is there a simpler way?
var1, var2, var3, var4 = l
This assumes l
is exactly 4 elements long. Most of the time, you want that, but if you don't,
var1, var2, var3, var4 = l[:4]
will ignore extra elements.
var1, var2, var3, var4 = alist
The number of names should be as many as the length of list, or there will be an error. If you have no need to have all the variables, you can use a for loop.
Use sequence unpacking on a slice of the list:
var1, var2, var3 = lst[:3]
If you want to unpack the whole list, you don't need to slice it:
var1, var2, var3 = lst
The last snippet will fail if lst
doesn't have exactly three elements.
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.