Python for循环内括号语法

2024-06-02 09:58:51 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我尝试将这个Python函数转换成Javascript。我不熟悉Python,所以有些语法对我来说很难加密。这是原始代码和我尝试的JS转换。我知道我解释错了,因为我现在所看到的是一个无限循环。在

Python:

graph = [[0,1,0,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,1,0,1,1],[1,1,0,1,0,0],[0,0,0,1,0,0]]

def N(vertex):
    c = 0
    l = []
    for i in graph[vertex]:
        if i is 1 :
         l.append(c)
        c+=1
    return l 

def bronk(r,p,x):
    if len(p) == 0 and len(x) == 0:
        print r
        return

    for vertex in p[:]:
        r_new = r[::]
        r_new.append(vertex)
        p_new = [val for val in p if val in N(vertex)] #this and
        x_new = [val for val in x if val in N(vertex)] #this part was particularly difficult to understand 
        bronk(r_new,p_new,x_new)
        p.remove(vertex)
        x.append(vertex)

bronk([], [0,1,2,3,4,5], [])

下面是我将其转换为JS的尝试:

^{pr2}$

我从this问题得到了Python代码。在

编辑:我在一个ES6环境中工作。在


Tags: 代码innewforlenreturnifdef
2条回答

它们都是python中的List comprehensions

在python中使用Javascript(没有ES6、babel及其关系)最接近于列表理解的方法是使用Array.Map(类似于python的map)

python示例

>>> l = [2, 4, 6, 8, 10, 12]
>>> [int(i / 2) for i in l]
[1, 2, 3, 4, 5, 6]

在Javascript中:

^{pr2}$

使用ES6中的Arrow functions,可以去掉{}

l.map(x => x/2)
[2, 4, 6, 8, 10, 12]

所以你的代码应该是这样的

const p_new = p.map(function(i){ if(i in N(vertex)){ return i } });
const x_new = x.map(function(i){ if(i in N(vertex)){ return i } });

最好使用:

p.filter(val => graph[vertex][val])

这样就减少了N所做的无用数组创建。在

而且~~不能正确地将-1转换为false和{}。。n到{}。请改用!!~。在

相关问题 更多 >