python中for循环的list最后一个数据总会覆盖前面的数据

查看:822
本文介绍了python中for循环的list最后一个数据总会覆盖前面的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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里面全部对象不是引用了同一个对象

解决方案

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

class lotto_result_cl:

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

即可

这篇关于python中for循环的list最后一个数据总会覆盖前面的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆