Reputation: 99
I am trying to write a function that will take a list of lists and print them out one by one with the word UNION between them. My code looks like this:
def printsql(lst):
print("INSERT INTO table")
for x in lst:
print("SELECT")
print(*x, sep=', ')
print("UNION")
return(str)
a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]
print(printsql(a))
My output currently looks like this:
INSERT INTO table
SELECT
1, 3, 4
UNION
SELECT
2, 5, 7
UNION
SELECT
3, 4, 6
UNION
This is almost exactly what I need but I can't figure out how to not print the last "UNION". Can someone advise?
Upvotes: 2
Views: 1694
Reputation: 103844
Consider using the .join
method in Python to insert a string between list elements.
Works like so:
>>> '|'.join(['a','b','c','d'])
'a|b|c|d'
Your example is essentially doing this:
[Header string "INSERT INTO table\nSELECT\n"]
'\nUNION\nSELECT\n'.join([list items])
', '.join([sub list items])
To get the pattern you describe.
You can take that description and translate to Python:
def printsql(lst):
s="INSERT INTO table\nSELECT\n"
s+="\nUNION\nSELECT\n".join(', '.join(str(e) for e in sl) for sl in lst)
return s
Then:
>>> a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]
>>> print(printsql(a))
INSERT INTO table
SELECT
1, 3, 4
UNION
SELECT
2, 5, 7
UNION
SELECT
3, 4, 6
The general outline is:
s="INSERT INTO table\nSELECT\n"
;join
to create the list of lists format of "\nUNION\nSELECT\n"
between the outer list elements and ', '
with the inner list elements;Upvotes: 2
Reputation: 133
This will remove the last union and class str
def printsql(lst):
print("INSERT INTO table")
counter = 0
for x in lst:
counter = counter + 1
print("SELECT")
print(*x, sep=', ')
if (len(lst)- 1) > counter:
print("UNION")
return("")
a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]
print(printsql(a))
Upvotes: 1
Reputation: 26039
This is one way avoiding an extra looping and condition:
def printsql(lst):
print("INSERT INTO table")
for x in lst[:-1]:
print("SELECT")
print(*x, sep=', ')
print("UNION")
print("SELECT")
print(*lst[-1], sep=', ')
return(str)
a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]
print(printsql(a))
'''
INSERT INTO table
SELECT
1, 3, 4
UNION
SELECT
2, 5, 7
UNION
SELECT
3, 4, 6
<class 'str'>
'''
Upvotes: 1
Reputation: 189
Quick and dirty.
def printsql(lst):
print("INSERT INTO table")
for x in lst:
if x != lst[-1]:
print("SELECT")
print(*x, sep=', ')
print("UNION")
else:
print("SELECT")
print(*x, sep=', ')
return(str)
a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]
print(printsql(a))
Upvotes: 0
Reputation: 1163
The brute force is to use enumerate
for idx, x in enumerate(lst):
#other stuff#
if idx<(len(lst) - 1):
print("UNION")
But I’d be interested to see if there is a more elegant solution.
Upvotes: 3