简体   繁体   English

将元组列表放入一个元组中,以逗号分隔导出到 SQL

[英]Put a list of tuples into one tuple separated by comma to export into SQL

I am hitting and looping through an API to collect various data into a variable called data .我正在点击并循环通过 API 将各种数据收集到一个名为data的变量中。 If I do print(data) I get the following:如果我print(data) ,我会得到以下信息:

('1111', 11, 'Test1', '2020-16-09', '123')
('2222', 22, 'Test2', '2020-16-09', '234')
('3333', 33, 'Test3', '2020-16-09', '345')

When I do print(type(data)) I get the following:当我执行print(type(data))时,我得到以下信息:

<class 'tuple'>
<class 'tuple'>
<class 'tuple'>

I need to put these tuples into one tuple separating each with a comma to look something like the below.我需要将这些元组放入一个元组中,每个元组用逗号分隔,如下所示。

( 
    ('1111', 11, 'Test1', '2020-16-09', '123'),
    ('2222', 22, 'Test2', '2020-16-09', '234'),
    ('3333', 33, 'Test3', '2020-16-09', '345') 
)

This it to allow me to export the data into SQL using cursor.executemany这允许我使用 cursor.executemany 将数据导出到cursor.executemany

Let's say you have a function api(x) that returns you the tuple for input x , and you know all the x you need to query, which is from a list X=[x1, x2, ...] , then you can get a tuple of tuple by this:假设您有一个 function api(x)返回输入x的元组,并且您知道所有需要查询的x ,它来自列表X=[x1, x2, ...] ,那么您可以通过这个得到一个元组的元组

tuple_of_tuples = tuple(api(x) for x in X)

but in the case of cursor.executemany() , many database library accepts an iterable as input, in that case, you can use a generator instead, which saves you memory in keeping all tuples:但在cursor.executemany()的情况下,许多数据库库接受可迭代作为输入,在这种情况下,您可以使用生成器代替,这样可以节省 memory 来保留所有元组:

generator_of_tuples = (api(x) for x in X)

Thanks everyone for your help, after doing some more digging around this is how I managed to get the data how I needed it.感谢大家的帮助,在做了更多的挖掘之后,我就是这样设法获得我需要的数据的。

jsondata = (multiple tuples) #my data from looping an API
    if b == 0: #b is my loop through the API
        finaldata = (jsondata,)
    else:
        finaldata = (jsondata,) + finaldata

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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