将联合正常形式的文件加载到列表列表中

时间:2013-01-10 09:31:33

标签: python conjunctive-normal-form

我编写了一些代码,用于根据描述的here标准从存储cnf的文件加载cnf。

文件是:

c  simple_v3_c2.cnf      // lines bigining by c are comments
c  
p cnf 3 2                // the line bigining by p is the description of the pb
1 -3 0                   // folowing lines are formulation of the pb, with 0 as ending caractere
2 3 -1 0

我想将其加载到[[1,-3] [2,3,-1]]

我写的代码有效,但对我来说似乎很难看。我想对它有一些反馈感兴趣。 (我是python的新手。)

def loadCnfFile(fileName='example.cnf'):
""" retourne une liste de listes d'entiers decrivants la forme normale conjonctive"""
cnf=[]
cnfFile = open(fileName, 'r')
for line in cnfFile:
    if line[0]!="c" and line[0]!="p":
        l=line.split("0")[0].strip().split(" ")
        m=[]
        for k in l:
            m.append(int(k))
        cnf.append(m)
cnfFile.close()
return cnf

谢谢!

3 个答案:

答案 0 :(得分:2)

我猜你的代码的最佳反馈是以更“pythonic”的方式重写它。例如:

def cnf_lines(path):
    """Yields cnf lines as lists from the file."""

    with open(path) as fp:
        for line in fp:
            if not line.startswith(('c', 'p')):
                items = map(int, line.split())
                yield items[:-1]

关键点:

  • PEP-8一致性(请在python中没有camelCase)
  • 文件操作的上下文管理器(with
  • 生成器(yield)而不是累积列表

注意:此代码是故意简化的,并不完全支持您链接的规范。

答案 1 :(得分:1)

使用list comprehension

In [66]: with open("example.cnf") as f:
        print [map(int,line.split("0")[0].split()) for line in f if line and \
                            not (line.startswith("c") or line.startswith("p"))]
   ....:     
[[1, -3], [2, 3, -1]]

或:

with open("example.cnf") as f:
         x= lambda y,c:y.startswith(c)
         print [map(int,line.split("0")[0].split()) for line in f if line and \
                                not any(x(line,z) for z in ("c","p"))]
   ....:     
[[1, -3], [2, 3, -1]]

答案 2 :(得分:1)

Ashwini的代码是正确的并且吸引了有经验的程序员(谢谢),但是对于一个刚接触python的人(你似乎是这样),也许一个简单的for循环更容易理解:

result = []
with open("example.cnf") as f:
    for line in f:
        if not (line.startswith("c") or line.startswith("p")):
            result.append([int(x) for x in line.rstrip("0").rstrip("0\n").split()])