问题
I try to store the number of weekofyear from the list of data named date_range which stored the data such as
date_range[1] = DatetimeIndex(['2020-03-02', '2020-03-03', '2020-03-04', '2020-03-05', '2020-03-06', '2020-03-07', '2020-03-08', '2020-03-09', '2020-03-10', '2020-03-11', '2020-03-12', '2020-03-13', '2020-03-14', '2020-03-15', '2020-03-16', '2020-03-17', '2020-03-18', '2020-03-19', '2020-03-20', '2020-03-21', '2020-03-22', '2020-03-23', '2020-03-24', '2020-03-25', '2020-03-26', '2020-03-27', '2020-03-28', '2020-03-29', '2020-03-30', '2020-03-31', '2020-04-01', '2020-04-02', '2020-04-03', '2020-04-04', '2020-04-05'], dtype='datetime64[ns]', freq='D')
by using the following code
weeknumber = [[0]*35]*2
for i in range(28):
for j in range(35)):
weeknumber[i][j]= pd.Timestamp(date_range[i][j]).weekofyear
However, the result of all 28 rows stored the last result of pd.Timestamp(date_range[28]).weekofyear
like this
So, How to fix it.
回答1:
0
is anint
object (in Python, everything is an object, remember). Let's call thisint
object as the "ZERO_OBJECT".[0]
is a list object having one element, and that element is a reference to the "ZERO_OBJECT". Let's call this list object "LIST_1"[0]*35
creates another list object, consisting of35
references to the same "ZERO_OBJECT". (That's how the*
operator works in Python). Let's call this new list object "LIST_2"[[0]*35]
is yet another list object having one element, and that element is a reference to the above object "LIST_2". Let's call this new list object "LIST_3"[[0]*35]*28
creates another list object, consisting of28
elements, but each of those28
elements is a reference to the same object "LIST_3". As I said above, that is how the*
operator works. (And you thought those28
elements were references to independent copies of "LIST_3"). This is definitely not what you wanted. Because, when you update one reference to "LIST_3", you will see it reflected via all other references to "LIST_3".
To fix this, use this code:
weeknumber = []
for i in range(28):
weeknumber.append([])
for j in range(35)):
weeknumber[i].append(pd.Timestamp(date_range[i][j]).weekofyear)
来源:https://stackoverflow.com/questions/64585708/how-to-fix-the-list-of-output-from-for-loop-always-store-the-last-value-of-last