I have a list of tuples in rows which I need to append to another list and add a newline after each entry I tried everything I can think of but I cant seem to do it properly here is the code:
niz = ["""
(5, 6, 4)
(90, 100, 13), (5, 8, 13), (9, 11, 13)
(9, 11, 5), (19, 20, 5), (30, 34, 5)
(9, 11, 4)
(22, 25, 13), (17, 19, 13)
"""]
list = []
for n in niz:
list.append(n)
list = '\n'.join(list)
print(list)
This is the closest I get:
(5, 6, 4)
(90, 100, 13), (5, 8, 13), (9, 11, 13)
(9, 11, 5), (19, 20, 5), (30, 34, 5)
(9, 11, 4)
(22, 25, 13), (17, 19, 13)
But I need it to be:
[(5, 6, 4),
(90, 100, 13), (5, 8, 13), (9, 11, 13),
(9, 11, 5), (19, 20, 5), (30, 34, 5),
(9, 11, 4),
(22, 25, 13), (17, 19, 13)]
CodePudding user response:
When you write
niz = ["""
(5, 6, 4)
(90, 100, 13), (5, 8, 13), (9, 11, 13)
(9, 11, 5), (19, 20, 5), (30, 34, 5)
(9, 11, 4)
(22, 25, 13), (17, 19, 13)
"""]
You are creating a list with a single string, and not a list of tuples. I would do something like this:
niz = ["[",(5, 6, 4), "\n", (90, 100, 13), (5, 8, 13), (9, 11, 13), "\n", (9, 11, 5), (19, 20, 5), (30, 34, 5), "\n", (9, 11, 4), "\n", (22, 25, 13), (17, 19, 13),"]"]
for item in niz:
print(item, end=" ")
CodePudding user response:
Here is what I suggest:
nizz = niz[0].replace(')\n(', '), (')
nizz = nizz.replace('), (', ')|(').replace('\n', '')
result = [eval(i) for i in nizz.split('|')]
It gives you the list of all tuples
CodePudding user response:
Join using ",\n" instead of just "\n"and append the first "[" and last "]" characters
list = []
for n in niz:
list.append(n)
list = '[' ',\n'.join(list) ']'
print(list)