python3循环只输出最后一个值,如何修复for循环的输出列表始终将最后一个索引的最后一个值存储在python中...

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

NPffT.jpg

So, How to fix it.

解决方案0 is an int object (in Python, everything is an object,

remember). Let's call this int 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 of 35 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 of 28 elements, but each of those 28 elements is a reference to the same object "LIST_3". As I said above, that is how the * operator works. (And you thought those 28 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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值