两个单独的python列表充当一个 [英] Two separate python lists acting as one

查看:89
本文介绍了两个单独的python列表充当一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究下面显示的代码以实现胆大.我试图弄清楚为什么当通过调用list(p)创建'g'时,列表'g'和'p'充当相同的列表.当在move函数中调用print语句(print [i] [j])时,表明更改'g'时将覆盖'p'.我刚刚开始使用python编程,希望对您有所帮助.预先感谢.

I've been working on the code shown below for udacity. I'm trying to figure out why the lists 'g' and 'p' are acting as the same list when 'g' is created by calling list(p). When the print statement (print[i][j]) is called in the move function it shows that 'p' is being overwritten when 'g' is changed. I just started programming in python and I would appreciate any help. Thanks in advance.

    colors = [['red', 'green', 'green', 'red' , 'red'],
      ['red', 'red', 'green', 'red', 'red'],
      ['red', 'red', 'green', 'green', 'red'],
      ['red', 'red', 'red', 'red', 'red']]

    measurements = ['green', 'green', 'green' ,'green', 'green']


    motions = [[0,0],[0,1],[1,0],[1,0],[0,1]]

    sensor_right = 0.7

    p_move = 0.8

    def show(p):
        for i in range(len(p)):
             print p[i]


    total = len(colors[0])*len(colors)
    for i in range(len(colors)):
        p.append([])
        for j in range(len(colors[i])):
            p[i].append(1./total)
    print p

    def move(g,c,r):
        t = list(g)
        for i in range(len(g)):
            for j in range(len(g[i])):
                print p[i][j]
                t[i][j] = t[(i-c)%len(g)][(j-r)%len(g[i])] * p_move
                print p[i][j]
        s = sum_table(t)
        for i in range(len(g)):
            for j in range(len(list(g[i]))):
                t[i][j] /= s
        return t 

    def sum_table(g):
        sum = 0
        for i in range(len(g)):
            for j in range(len(g[i])):
                sum += g[i][j]
        print sum
        return sum


    move(list(p),0,1)
    print p

推荐答案

我没有详细介绍您的代码,但是麻烦的根源很可能是使用了二维数据结构(列表列表).在Python中,list()构造函数是 shallow copy ,它仅复制一个级别的列表.您可以在适当的地方使用 copy.deepcopy() 函数来避免遇到的问题.

I haven't followed through your code in detail, but the source of your trouble is likely the use of two dimensional data structures (lists of lists). In Python, the list() constructor is a shallow copy, which only copies one level of list. You may be able to avoid the problem you're seeing using the copy.deepcopy() function where appropriate.

一个技巧是使用id(p)id(g)来找出每个引用的 actual 对象标识是什么.这种调试可以帮助您隔离问题.您经常调用list()构造函数,可能远远超出了必要.这样创建不必要的数据结构副本将为CPU带来更多工作,并可能影响性能关键代码.

One trick is to use id(p) and id(g) to find out what the actual object identity is for each reference. This sort of debugging may help isolate your problem. You're calling the list() constructor a lot, probably much more than necessary. Creating unnecessary copies of data structures like this will make much more work for the CPU and can affect performance critical code.

这篇关于两个单独的python列表充当一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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