-2

I have to lists as below:

list1 = [[33, 35, 50, 52, 67, 69, 82, 84, 86, 99],
         [01, 16, 18, 35, 50, 52, 67, 69, 84, 08]]

I would like to have this as the output:

['select * from table where id in (33, 35, 50, 52, 67, 69, 82, 84, 86, 99)', 'select * from table where id in (01, 16, 18, 35, 50, 52, 67, 69, 84, 08)']

would appreciate your help :)

The Thonnu
  • 3,578
  • 2
  • 8
  • 30

3 Answers3

0
list1 = [[33, 35, 50, 52, 67, 69, 82, 84, 86, 99], [1, 16, 18, 35, 50, 52, 67, 69, 84, 8]]

new_list = []

for sub_list in list1:
    new_list.append(f"select * from table where id in {tuple(sub_list)}")

print(new_list)

Output:

['select * from table where id in (33, 35, 50, 52, 67, 69, 82, 84, 86, 99)', 'select * from table where id in (1, 16, 18, 35, 50, 52, 67, 69, 84, 8)']

Careful with 01 and 08 instead of 1 and 8, this would raise an error.

Apo
  • 338
  • 1
  • 9
0

This is a good task for list comprehension:

command = "select * from table where id in"
new_list = [f"{command} ({', '.join([str(i) for i in sub_list])})" for sub_list in list1]

This code shows how to form the target string. It can be useful if the parenthesis are of some other type.

Hihikomori
  • 950
  • 6
  • 12
0

You can convert it to a tuple to get that parentheses layout, and then a string to add it to the select statement.

list1 = [[33, 35, 50, 52, 67, 69, 82, 84, 86, 99],
         [1, 16, 18, 35, 50, 52, 67, 69, 84, 8]]

newList = []
for i in list1:
    newList.append("select * from table where id in " + str(tuple(i)))
print(newList)

You will need to remove the leading 0's before the 1 and 8 though, otherwise you will get an error.

cupoftea
  • 69
  • 11