简体   繁体   English

将多个元组组合成一个元组列表

[英]Combine multiple tuples into a list of tuples

I have a series of tuples that are outputed from looping through the results of a SQL query, and its parameters.我有一系列从循环 SQL 查询的结果及其参数输出的元组。 So far, I have:到目前为止,我有:

  Answers = ((userId, p[0], questions, i[0]) for i in strQueryTemplateForAnswerColumn)
            AnswerList = []
            for i in Answers:
                AnswerList.append(i)
                print(AnswerList)

Resulting in:导致:

[(42, 1, 1, 3)]
[(296, 1, 1, 5)]
[(1358, 1, 1, -1)].....etc for a few thousand rows.

What I am trying to do is combine these tuples into one list of tuples rather than each tuple being converted to a list.我想要做的是将这些元组组合成一个元组列表,而不是将每个元组转换为一个列表。 Such as:如:

[(42, 1, 1, 3), (296, 1, 1, 5), (1358, 1, 1, -1)]

This is in order convert it to a pandas df eventually, with 4 columns/headers.这是为了最终将其转换为具有 4 列/标题的 pandas df。

Here is the entire code for reference:以下是供参考的完整代码:

cursor = conn.cursor()
allSurveyID = cursor.execute("""SELECT SurveyId FROM dbo.[Survey]""").fetchall()

for a in allSurveyID:
p = a
currentSurveyIDs = cursor.execute("""
DECLARE @SurveyID INT = ?
                SELECT *
           FROM
           (
              SELECT
                 SurveyId,
                 QuestionId,
                 1 as InSurvey
              FROM
                 SurveyStructure
              WHERE
                 SurveyId = @SurveyID
              UNION
              SELECT 
                 @SurveyID as SurveyId,
                 Q.QuestionId,
                 0 as InSurvey
              FROM
                 Question as Q
              WHERE NOT EXISTS
              (
                 SELECT *
                 FROM SurveyStructure as S
                 WHERE S.SurveyId = @SurveyID AND S.QuestionId = Q.QuestionId
              )
           ) as t
           ORDER BY QuestionId
            """, p).fetchall()

    for b in currentSurveyIDs:
        survey = (b[0])
        questions = (b[1])
        InSurvey = (b[2])

        allUserID = cursor.execute("""SELECT UserId FROM dbo.[Answer] ORDER BY 
UserId""").fetchall()

        for i in allUserID:
            userId = i[0]

            if InSurvey == 1:
                strQueryTemplateForAnswerColumn = cursor.execute("""SELECT COALESCE 
                                  ((SELECT 
                                   a.Answer_Value
                                   FROM dbo.Answer a 
                                   WHERE a.UserId = ?
                                   AND a.SurveyId = ?
                                   AND a.QuestionId = ?
                                   ),-1) AS ANS_Q?""", userId, survey, questions, questions).fetchall()

                    Answers = ((userId, p[0], questions, i[0]) for i in 
                                        strQueryTemplateForAnswerColumn)
                    AnswerList = []
                    for i in Answers:
                       AnswerList.append(i)
                       print(AnswerList)

Thank you for any input感谢您的任何输入

I think you're saying you have a list of things like [(42, 1, 1, 3)] and you want to convert it to a list of things like (42, 1, 1, 3) .我认为您是说您有一个诸如[(42, 1, 1, 3)]之类的列表,并且您想将其转换为诸如(42, 1, 1, 3)之类的列表。

You can do this:你可以这样做:

listOfListOfTuples = [
    [(42, 1, 1, 3)],
    [(296, 1, 1, 5)],
    [(1358, 1, 1, -1)]
]

print(listOfListOfTuples)

listOfTuples = [x[0] for x in listOfListOfTuples]
print(listOfTuples)

Input:输入:

[[(42, 1, 1, 3)], [(296, 1, 1, 5)], [(1358, 1, 1, -1)]]

Output:输出:

[(42, 1, 1, 3), (296, 1, 1, 5), (1358, 1, 1, -1)]

Thank you for your comments.谢谢您的意见。 This worked.这行得通。

AnswerCol = []
AnswerColNull = []

# Loop through Survey and retrieve SurveyIDs while executing query to return the SurveyIDs, QuestionIDs and whether
# the question is in the survey

for a in allSurveyID:
    p = a[0]
    currentSurveyIDs = cursor.execute("""

                    SELECT *
               FROM
               (
                  SELECT
                     SurveyId,
                     QuestionId,
                     1 as InSurvey
                  FROM
                     SurveyStructure
                  WHERE
                     SurveyId = ?
                  UNION
                  SELECT 
                     ? as SurveyId,
                     Q.QuestionId,
                     0 as InSurvey
                  FROM
                     Question as Q
                  WHERE NOT EXISTS
                  (
                     SELECT *
                     FROM SurveyStructure as S
                     WHERE S.SurveyId = ? AND S.QuestionId = Q.QuestionId
                  )
               ) as t
               ORDER BY QuestionId
                """, p, p, p).fetchall()

    # Assign columns from above query to variables
    for b in currentSurveyIDs:
        survey = (b[0])
        questions = (b[1])
        InSurvey = (b[2])

        # Get all UserIDs and assign to variable
        allUserID = cursor.execute("""SELECT UserId FROM dbo.[Answer] ORDER BY UserId""").fetchall()
        for c in allUserID:
            userId = c[0]

            # If the question is in the survey, proceed with the AnswerColumn template query
            if InSurvey == 1:

                strQueryTemplateForAnswerColumn = cursor.execute("""SELECT COALESCE 
                                      ((SELECT 
                                       a.Answer_Value
                                       FROM dbo.Answer a 
                                       WHERE a.UserId = ?
                                       AND a.SurveyId = ?
                                       AND a.QuestionId = ?
                                       ),-1) AS ANS_Q?""", userId, survey, questions, questions).fetchall()

                # Generate rows for the table by appending each value to a list, creating a row then appending
                # the rows to a list outside the for loop
                Answer_List = []
                for d in strQueryTemplateForAnswerColumn:
                    Answer_parts = userId, p, questions, d[0]
                    Answer_List.append(Answer_parts)
                AnswerColNull.append(Answer_List)

            # Same procedure for the NULL values: if the question is not in the survey, use NULL answer template
            # query
            elif InSurvey == 0:
                strQueryTemplateForNullColumnn = cursor.execute(""" SELECT NULL AS ANS_?""",
                                                                questions).fetchall()
                # Generate rows for the table by appending each value to a list, creating a row then appending
                # the rows to a list outside the for loop
                Answer_ListNull = []
                for e in strQueryTemplateForNullColumnn:
                    Answer_partsNull = userId, p, questions, e[0]
                    Answer_ListNull.append(Answer_partsNull)
                AnswerColNull.append(Answer_ListNull)

# Append the values only of each list, cast to a tuple then appended to another list
AnswerColValsNull = []
for f in AnswerColNull:
    AnswerColValsNull.append(tuple(f[0]))

AnswerColVals = []
for g in AnswerCol:
    AnswerColVals.append(tuple(g[0]))

# Combine the list containing UserID, SurveyID, QuestionID, and Answer_Value
# At this point all the information is in a list of tuples
final = AnswerColVals + AnswerColValsNull

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

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