将for循环转换为while循环并将List Comprehension转换为无List Insrehension

时间:2017-11-07 16:35:17

标签: python python-3.x for-loop while-loop list-comprehension

我自己开始在线学习Python。使用List和for循环创建以下程序,以计算函数输入中的节点和边。遵循这个:http://mathworld.wolfram.com/GridGraph.html简单的规则来生成节点和边。是否有可能仅使用While和数组而不是for循环和List理解在Python中创建相同的程序?你能介意给我这个吗?

def gridGen(a,b):
    return [
            [(x,y) for y in range(0,a)] 
        for x in range(0,b)
    ]

def edgeListGen(grid):
    edgeList = []
    for y, row in enumerate(grid):
        for x, val in enumerate(row):
            if (x < len(row)-1):
                edgeList.append(((x,y),(x+1,y)))
            if (y < len(grid)-1):
                edgeList.append(((x,y),(x,y+1)))
    return edgeList

def printGrid(grid):
    for line in grid:
        for value in line:
            print(value, end=' ')
        print()
    print()       

def printEdgeList(L):
    for edge in edgeList:
        print(edge[0], ',', edge[1])

grid=gridGen(5,2)
printGrid(grid)

edgeList=edgeListGen(grid)
printEdgeList(edgeList)

输出:

(0, 0) (0, 1) (0, 2) (0, 3) (0, 4) 
(1, 0) (1, 1) (1, 2) (1, 3) (1, 4) 

(0, 0) , (1, 0)
(0, 0) , (0, 1)
(1, 0) , (2, 0)
(1, 0) , (1, 1)
(2, 0) , (3, 0)
(2, 0) , (2, 1)
(3, 0) , (4, 0)
(3, 0) , (3, 1)
(4, 0) , (4, 1)
(0, 1) , (1, 1)
(1, 1) , (2, 1)
(2, 1) , (3, 1)
(3, 1) , (4, 1)

1 个答案:

答案 0 :(得分:0)

Python不支持开箱即用的多维数组,但您可以通过numpy轻松完成此操作。

例如,{ "name": "tests", "version": "0.0.1", "description": "Test for testing.", "main": "index.js", "license": "UNLICENSED", "dependencies": { "chromedriver": "^2.0", "cucumber": "^3.1", "selenium-webdriver": "^3.0" }, "devDependencies": { } } 将成为:

gridGen