Python assigning multiple variables to same list v

2020-06-03 00:26发布

I'm writing a function to calculate calendar dates. While cutting down on lines, I've found that I am unable to assign multiple variables to the same range.

Jan, Mar, May, Jul, Aug, Oct, Dec = range(1,32)

Would there be an efficient way to assign these values and why does python give a ValueError?

标签: python list
2条回答
Anthone
2楼-- · 2020-06-03 01:12

Use

Jan = Mar = May = ... = range(1, 32)
查看更多
家丑人穷心不美
3楼-- · 2020-06-03 01:26

The easiest way to do what you described would be to use the x=y=z ... = VALUE syntax, where x, y, z, and any other variables you include will all be assigned the value of VALUE.

In your example, all the comma-separated variables on the left side of the equals sign are assigned to sequential values of a tuple on the right side. Hence, you could do something like this:

values = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec = values

In your code, you have 7 values on the left, and 31 on the right, so you get an out of range error because the list on the left is longer than the number or variables on the left side to be assigned the values in it. I know the code above doesn't have much relevance to achieving your goal, but I thought I'd at least give some insight as to what it was trying to do. :D

查看更多
登录 后发表回答