python中for循环的list最后一个数据总会覆盖前面的数据
阿神
阿神 2017-04-18 10:17:58
[Python讨论组]

1.如题,我真的是没办法了,用尽各种方法list的最后一个数据都会覆盖前面的数据。
2.

class lotto_result_cl:
    def __init__(self, index, spe_p):
        lotto_result_cl.index = index
        lotto_result_cl.spe = spe_p

spe_nums_int =[47, 13, 43]
spe_cl_list = []

for i in range(len(spe_nums_int)):
    spe_cl_list.append(lotto_result_cl(i+1, spe_nums_int[i]))

for i in range(len(spe_cl_list)):
    print spe_cl_list[i].index
    print spe_cl_list[i].spe

3.结果:

3
43
3
43
3
43
但是我要的结果是:
1
47
2
13
3
43

内存分布:

<__main__.lotto_result_cl instance at 0x01724968>
<__main__.lotto_result_cl instance at 0x01724990>
<__main__.lotto_result_cl instance at 0x017249B8>

证明list里面全部对象不是引用了同一个对象

阿神
阿神

闭关修行中......

全部回复(1)
怪我咯

你这个类的init有问题,对之前创造的实例进行了修改,应为

class lotto_result_cl:

def __init__(self, index, spe_p):
    self.index = index
    self.spe = spe_p

即可

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号