pythonlistcnf

Python - Output a list datatype to CNF


I have a list as:

KB = [['~p', '~r', 's'], ['~r', 'k'], ['~k', 'm'], ['r'], ['~m'], ['~p', 'r']]

I need to output to a file ('output.txt') with CNF format such like this:

~p|~r|s
~r|k
~k|m
r
~m
~p|r

So what should I do now?


Solution

  • BearBrown's comment covers the most important part of the problem. I am adapting to it show how to write to file after joining pipe ('|') as needed.

    KB = [['~p', '~r', 's'], ['~r', 'k'], ['~k', 'm'], ['r'], ['~m'], ['~p', 'r']]
    
    p = ["|".join(x) for x in KB]
    
    with open('output.txt') as o:
        for item in p:
            o.write('%s\n' % item)