2D列表以1D

时间:2015-10-12 22:48:12

标签: python python-3.x

给出输入

实施例: runGenerations2d([[0, 0, 1, 0], [0, 0, 1, 1], [1, 1, 1, 0], [1, 0, 0, 1]])

点击任意一个框,程序会将数字从1转换为0,否则为0到1.问题出现在点击后传回runGenerations2d的信息进入一维列表而不是原始列表2D列表。我认为导致问题的函数是evolve2d

关于我在哪里出错的任何建议?

import time # provides time.sleep(0.5)
from csplot import * # provides the visual board
from random import * # provides choice( [0,1] ), etc.
import sys  # larger recursive stack
sys.setrecursionlimit(100000) # 100,000 deep


def runGenerations2d(L , x=0 ,y=0 ):
    show(L)
    print( L )           # display the list, L
    time.sleep(5)      # pause a bit
    newL = evolve2d( L )   # evolve L into newL
    print(newL)
    if min(L) == 1:
        #I like read outs to be explained so I added an extra print command.
        if x<=1: # Takes into account the possibility of a 1 click completition.
            print ('BaseCase Reached!... it took %i click to complete' % (x))
            print (x)
            done()#removes the need to input done() into the shell
        else:
            print ('BaseCase Reached!... it took %i clicks to complete' % (x))
            print (x)
            done()#removes the need to input done() into the shell
        return   
    x = x+1 # add 1 to x before every recusion
    runGenerations2d( newL , x,y )  # recurse

def evolve2d( L ):
    N = len(L)
    x,y = sqinput2()
    print(x,y)
    show(L)
    print("Two")
    time.sleep(5)
    return [setNewElement2d(L, xx, yy, x, y) for xx in range(N) for yy in range(N)]


def setNewElement2d( L, xx, yy, x=0,y=0 ):
    show(L)
    print(L)
    print("Three")
    #time.sleep(5)    
    if (xx,yy) == (x,y): # if it's the user's chosen row and column
        if L[xx][yy]==1:
            return 0 
        else:
            return 1 # If it's already 1 return 0 else return 1
    else: # otherwise
        print("Lastly")
        return L[xx][yy] # return the original  

给出错误:

[[0, 0, 1, 0], [0, 0, 1, 1], [1, 1, 1, 0], [1, 0, 0, 1]]
Three
Lastly
[0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1]
[0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1]
The data does not seem 2d.
Try using sqinput instead.

1 个答案:

答案 0 :(得分:1)

如Brian所述,创建一个2D列表理解:

[[... for ... in ...] for ... in ...] 

而不是一维列表理解:

[... for ... in ... for ... in ...]