简体   繁体   中英

python list containing ID in sql query as parameter

I have an ID list

id = [339, 344, 340, 343, 345, 342, 341]

already select as in the way in this link here , this is the code

mycursor.execute("SELECT * FROM news_tb where id IN ({})".format(",".join([str(i) for i in hasil])))

but the results are in sequence

[(339, '..'), (340, '..'), (341, '..'), (342, '..'), (343, '..'), (344, '..'), (345, '..')]

I want the data output to be sequential according to the id in the list. Thankyou

结果 = 排序(结果,键 = lambda x: id.index(x[0]))

Assuming your results are in results ,

r_dict = dict([r[0],r[1:]] for r in results)
ordered_results = [tuple([i]+list(r_dict[i])) for i in id]
print(ordered_results)

will print the desired list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM