首页 > 解决方案 > 如何为每次迭代创建一个带有附加的独立列表?

问题描述

我通过 API 获得以下原始数据:

[{'landing_id': '5rjqwlrxzzcve5s7ip05rjqw531fyk9q', 'token': '5rjqwlrxzzcve5s7ip05rjqw531fyk9q', 'response_id': '5rjqwlrxzzcve5s7ip05rjqw531fyk9q', 'landed_at': '2021-08-27T13:50:18Z', 'submitted_at': '2021-08-27T13:50:49Z', 'metadata': {'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36', 'platform': 'other', 'referer': 'https://form.typeform.com/to/znd02BPL?typeform-source=localhost', 'network_id': 'd9b4f41014', 'browser': 'default'}, 'hidden': {}, 'calculated': {'score': 0}, 'answers': [{'field': {'id': 'rwNldsS8H1Uu', 'ref': '01FD00Z0842DNV2F7TV5S034FB', 'type': 'short_text'}, 'type': 'text', 'text': 'Asdflasdfjkasdf'}, {'field': {'id': 'HmiYDva4iYTJ', 'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08', 'type': 'short_text'}, 'type': 'text', 'text': 'ASdflasdfkö'}, {'field': {'id': 'zCNV4nksvT7C', 'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5', 'type': 'email'}, 'type': 'email', 'email': 'philipp@ganster.com'}]}, {'landing_id': 'mnpxvbgbmgi0aut64g7mnpxvb1a66lb1', 'token': 'mnpxvbgbmgi0aut64g7mnpxvb1a66lb1', 'response_id': 'mnpxvbgbmgi0aut64g7mnpxvb1a66lb1', 'landed_at': '2021-08-24T13:33:01Z', 'submitted_at': '2021-08-24T13:33:16Z', 'metadata': {'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36', 'platform': 'other', 'referer': 'https://form.typeform.com/to/znd02BPL', 'network_id': '1b607e2e2c', 'browser': 'default'}, 'hidden': {}, 'calculated': {'score': 0}, 'answers': [{'field': {'id': 'rwNldsS8H1Uu', 'ref': '01FD00Z0842DNV2F7TV5S034FB', 'type': 'short_text'}, 'type': 'text', 'text': 'Alles cool'}, {'field': {'id': 'HmiYDva4iYTJ', 'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08', 'type': 'short_text'}, 'type': 'text', 'text': 'Cool cooli cooli'}, {'field': {'id': 'zCNV4nksvT7C', 'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5', 'type': 'email'}, 'type': 'email', 'email': 'cool@cool.de'}]}, {'landing_id': 'v2szjmf3by92rzpcyt6gxzv2szjmf3gj', 'token': 'v2szjmf3by92rzpcyt6gxzv2szjmf3gj', 'response_id': 'v2szjmf3by92rzpcyt6gxzv2szjmf3gj', 'landed_at': '2021-08-24T12:35:25Z', 'submitted_at': '2021-08-24T12:35:52Z', 'metadata': {'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36', 'platform': 'other', 'referer': 'https://form.typeform.com/to/znd02BPL', 'network_id': '1b607e2e2c', 'browser': 'default'}, 'hidden': {}, 'calculated': {'score': 0}, 'answers': [{'field': {'id': 'rwNldsS8H1Uu', 'ref': '01FD00Z0842DNV2F7TV5S034FB', 'type': 'short_text'}, 'type': 'text', 'text': 'Wir sind die Besten weltweit'}, {'field': {'id': 'HmiYDva4iYTJ', 'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08', 'type': 'short_text'}, 'type': 'text', 'text': 'Sehr freundlich aber hart im Ton'}, {'field': {'id': 'zCNV4nksvT7C', 'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5', 'type': 'email'}, 'type': 'email', 'email': 'elisa@andyduke.com'}]}, {'landing_id': '9nquhgyp7dtddqxzj8mg9nquh5tsernm', 'token': '9nquhgyp7dtddqxzj8mg9nquh5tsernm', 'response_id': '9nquhgyp7dtddqxzj8mg9nquh5tsernm', 'landed_at': '2021-08-17T19:33:29Z', 'submitted_at': '2021-08-17T19:33:47Z', 'metadata': {'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36', 'platform': 'other', 'referer': 'https://form.typeform.com/to/znd02BPL', 'network_id': '8b083c318f', 'browser': 'default'}, 'hidden': {}, 'calculated': {'score': 0}, 'answers': [{'field': {'id': 'rwNldsS8H1Uu', 'ref': '01FD00Z0842DNV2F7TV5S034FB', 'type': 'short_text'}, 'type': 'text', 'text': 'Wir haben keins'}, {'field': {'id': 'HmiYDva4iYTJ', 'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08', 'type': 'short_text'}, 'type': 'text', 'text': 'Nicht so gut'}, {'field': {'id': 'zCNV4nksvT7C', 'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5', 'type': 'email'}, 'type': 'email', 'email': 'ganster95@gmail.com'}]}, {'landing_id': '6y29hqnt2kr3nwtun6y292j5ede7kluc', 'token': '6y29hqnt2kr3nwtun6y292j5ede7kluc', 'response_id': '6y29hqnt2kr3nwtun6y292j5ede7kluc', 'landed_at': '2021-08-16T15:25:52Z', 'submitted_at': '2021-08-16T15:26:44Z', 'metadata': {'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36', 'platform': 'other', 'referer': 'https://5elebf29vtz.typeform.com/to/znd02BPL', 'network_id': 'f46ac8439a', 'browser': 'default'}, 'hidden': {}, 'calculated': {'score': 0}, 'answers': [{'field': {'id': 'rwNldsS8H1Uu', 'ref': '01FD00Z0842DNV2F7TV5S034FB', 'type': 'short_text'}, 'type': 'text', 'text': 'Wir sind beraten, installieren und konfigurieren die besten Solarzellen'}, {'field': {'id': 'HmiYDva4iYTJ', 'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08', 'type': 'short_text'}, 'type': 'text', 'text': 'Sehr druckvoll, aber auch liebevoll. Wir sind die Besten mit Herz und Seele.'}, {'field': {'id': 'zCNV4nksvT7C', 'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5', 'type': 'email'}, 'type': 'email', 'email': 'philipp.ganster95@gmail.com'}]}]

为了更好地阅读,我使用了 pprint 包,以结构化的方式显示数据(但是,上面的数据用于我的函数,因为它是一个列表,而 pprint 包将其说明为字典 - 所以这可能是一个有点误导):

{'items': [{'answers': [{'field': {'id': 'rwNldsS8H1Uu',
                                   'ref': '01FD00Z0842DNV2F7TV5S034FB',
                                   'type': 'short_text'},
                         'text': 'Asdflasdfjkasdf',
                         'type': 'text'},
                        {'field': {'id': 'HmiYDva4iYTJ',
                                   'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08',
                                   'type': 'short_text'},
                         'text': 'ASdflasdfkö',
                         'type': 'text'},
                        {'email': 'philipp@ganster.com',
                         'field': {'id': 'zCNV4nksvT7C',
                                   'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5',
                                   'type': 'email'},
                         'type': 'email'}],
            'calculated': {'score': 0},
            'hidden': {},
            'landed_at': '2021-08-27T13:50:18Z',
            'landing_id': '5rjqwlrxzzcve5s7ip05rjqw531fyk9q',
            'metadata': {'browser': 'default',
                         'network_id': 'd9b4f41014',
                         'platform': 'other',
                         'referer': 'https://form.typeform.com/to/znd02BPL?typeform-source=localhost',
                         'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X '
                                       '10_15_7) AppleWebKit/537.36 (KHTML, '
                                       'like Gecko) Chrome/92.0.4515.159 '
                                       'Safari/537.36'},
            'response_id': '5rjqwlrxzzcve5s7ip05rjqw531fyk9q',
            'submitted_at': '2021-08-27T13:50:49Z',
            'token': '5rjqwlrxzzcve5s7ip05rjqw531fyk9q'},
           {'answers': [{'field': {'id': 'rwNldsS8H1Uu',
                                   'ref': '01FD00Z0842DNV2F7TV5S034FB',
                                   'type': 'short_text'},
                         'text': 'Alles cool',
                         'type': 'text'},
                        {'field': {'id': 'HmiYDva4iYTJ',
                                   'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08',
                                   'type': 'short_text'},
                         'text': 'Cool cooli cooli',
                         'type': 'text'},
                        {'email': 'cool@cool.de',
                         'field': {'id': 'zCNV4nksvT7C',
                                   'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5',
                                   'type': 'email'},
                         'type': 'email'}],
            'calculated': {'score': 0},
            'hidden': {},
            'landed_at': '2021-08-24T13:33:01Z',
            'landing_id': 'mnpxvbgbmgi0aut64g7mnpxvb1a66lb1',
            'metadata': {'browser': 'default',
                         'network_id': '1b607e2e2c',
                         'platform': 'other',
                         'referer': 'https://form.typeform.com/to/znd02BPL',
                         'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X '
                                       '10_15_7) AppleWebKit/537.36 (KHTML, '
                                       'like Gecko) Chrome/92.0.4515.159 '
                                       'Safari/537.36'},
            'response_id': 'mnpxvbgbmgi0aut64g7mnpxvb1a66lb1',
            'submitted_at': '2021-08-24T13:33:16Z',
            'token': 'mnpxvbgbmgi0aut64g7mnpxvb1a66lb1'},
           {'answers': [{'field': {'id': 'rwNldsS8H1Uu',
                                   'ref': '01FD00Z0842DNV2F7TV5S034FB',
                                   'type': 'short_text'},
                         'text': 'Wir sind die Besten weltweit',
                         'type': 'text'},
                        {'field': {'id': 'HmiYDva4iYTJ',
                                   'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08',
                                   'type': 'short_text'},
                         'text': 'Sehr freundlich aber hart im Ton',
                         'type': 'text'},
                        {'email': 'elisa@andyduke.com',
                         'field': {'id': 'zCNV4nksvT7C',
                                   'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5',
                                   'type': 'email'},
                         'type': 'email'}],
            'calculated': {'score': 0},
            'hidden': {},
            'landed_at': '2021-08-24T12:35:25Z',
            'landing_id': 'v2szjmf3by92rzpcyt6gxzv2szjmf3gj',
            'metadata': {'browser': 'default',
                         'network_id': '1b607e2e2c',
                         'platform': 'other',
                         'referer': 'https://form.typeform.com/to/znd02BPL',
                         'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X '
                                       '10_15_7) AppleWebKit/537.36 (KHTML, '
                                       'like Gecko) Chrome/92.0.4515.159 '
                                       'Safari/537.36'},
            'response_id': 'v2szjmf3by92rzpcyt6gxzv2szjmf3gj',
            'submitted_at': '2021-08-24T12:35:52Z',
            'token': 'v2szjmf3by92rzpcyt6gxzv2szjmf3gj'},
           {'answers': [{'field': {'id': 'rwNldsS8H1Uu',
                                   'ref': '01FD00Z0842DNV2F7TV5S034FB',
                                   'type': 'short_text'},
                         'text': 'Wir haben keins',
                         'type': 'text'},
                        {'field': {'id': 'HmiYDva4iYTJ',
                                   'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08',
                                   'type': 'short_text'},
                         'text': 'Nicht so gut',
                         'type': 'text'},
                        {'email': 'ganster95@gmail.com',
                         'field': {'id': 'zCNV4nksvT7C',
                                   'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5',
                                   'type': 'email'},
                         'type': 'email'}],
            'calculated': {'score': 0},
            'hidden': {},
            'landed_at': '2021-08-17T19:33:29Z',
            'landing_id': '9nquhgyp7dtddqxzj8mg9nquh5tsernm',
            'metadata': {'browser': 'default',
                         'network_id': '8b083c318f',
                         'platform': 'other',
                         'referer': 'https://form.typeform.com/to/znd02BPL',
                         'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X '
                                       '10_15_7) AppleWebKit/537.36 (KHTML, '
                                       'like Gecko) Chrome/92.0.4515.131 '
                                       'Safari/537.36'},
            'response_id': '9nquhgyp7dtddqxzj8mg9nquh5tsernm',
            'submitted_at': '2021-08-17T19:33:47Z',
            'token': '9nquhgyp7dtddqxzj8mg9nquh5tsernm'},
           {'answers': [{'field': {'id': 'rwNldsS8H1Uu',
                                   'ref': '01FD00Z0842DNV2F7TV5S034FB',
                                   'type': 'short_text'},
                         'text': 'Wir sind beraten, installieren und '
                                 'konfigurieren die besten Solarzellen',
                         'type': 'text'},
                        {'field': {'id': 'HmiYDva4iYTJ',
                                   'ref': '005e2b9d-2ffa-4102-b8ad-7f5245677b08',
                                   'type': 'short_text'},
                         'text': 'Sehr druckvoll, aber auch liebevoll. Wir '
                                 'sind die Besten mit Herz und Seele.',
                         'type': 'text'},
                        {'email': 'philipp.ganster95@gmail.com',
                         'field': {'id': 'zCNV4nksvT7C',
                                   'ref': '2bdaadb8-e4ed-4cb3-bdf6-9c93c2a70ed5',
                                   'type': 'email'},
                         'type': 'email'}],
            'calculated': {'score': 0},
            'hidden': {},
            'landed_at': '2021-08-16T15:25:52Z',
            'landing_id': '6y29hqnt2kr3nwtun6y292j5ede7kluc',
            'metadata': {'browser': 'default',
                         'network_id': 'f46ac8439a',
                         'platform': 'other',
                         'referer': 'https://5elebf29vtz.typeform.com/to/znd02BPL',
                         'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X '
                                       '10_15_7) AppleWebKit/537.36 (KHTML, '
                                       'like Gecko) Chrome/92.0.4515.131 '
                                       'Safari/537.36'},
            'response_id': '6y29hqnt2kr3nwtun6y292j5ede7kluc',
            'submitted_at': '2021-08-16T15:26:44Z',
            'token': '6y29hqnt2kr3nwtun6y292j5ede7kluc'}],
 'page_count': 1,
 'total_items': 5}

我的用例:

我想检索 response_id、用户的电子邮件和每个响应的所有答案。为此,我已经编写了以下函数(RESPS 变量包含上述所有数据):

def structure_response (RESPS): # returns response ID, user e-mail and answers
    
    answers = []
    count = 1
        
    for i in RESPS: # loops through list of responses containing dictionaries
        
        for key, value in i.items():
            
            if key == "response_id": # returns response_id
                response_id = value
        
            if key == "answers": # returns email
                user_email = value[-1]["email"]
            
                for j in value: # returns answers | value is a list containing dictionaries                 
                    for key, value in j.items():
                        if key == "text":
                            answers.append(value)
        
        #Print Output
        print("Response {} :".format(count))
        print("Response ID: " + str(response_id))
        print("User's E-Mail Adress: " + str(user_email))
        print("Answers : " + str(answers))                   
        print("\n")
        count += 1
        


# Call Function
structure_response(RESPS)

输出:

Response 1 :
Response ID: 5rjqwlrxzzcve5s7ip05rjqw531fyk9q
User's E-Mail Adress: philipp@ganster.com
Answers : ['Asdflasdfjkasdf', 'ASdflasdfkö']


Response 2 :
Response ID: mnpxvbgbmgi0aut64g7mnpxvb1a66lb1
User's E-Mail Adress: cool@cool.de
Answers : ['Asdflasdfjkasdf', 'ASdflasdfkö', 'Alles cool', 'Cool cooli cooli']


Response 3 :
Response ID: v2szjmf3by92rzpcyt6gxzv2szjmf3gj
User's E-Mail Adress: elisa@andyduke.com
Answers : ['Asdflasdfjkasdf', 'ASdflasdfkö', 'Alles cool', 'Cool cooli cooli', 'Wir sind die Besten weltweit', 'Sehr freundlich aber hart im Ton']


Response 4 :
Response ID: 9nquhgyp7dtddqxzj8mg9nquh5tsernm
User's E-Mail Adress: ganster95@gmail.com
Answers : ['Asdflasdfjkasdf', 'ASdflasdfkö', 'Alles cool', 'Cool cooli cooli', 'Wir sind die Besten weltweit', 'Sehr freundlich aber hart im Ton', 'Wir haben keins', 'Nicht so gut']


Response 5 :
Response ID: 6y29hqnt2kr3nwtun6y292j5ede7kluc
User's E-Mail Adress: philipp.ganster95@gmail.com
Answers : ['Asdflasdfjkasdf', 'ASdflasdfkö', 'Alles cool', 'Cool cooli cooli', 'Wir sind die Besten weltweit', 'Sehr freundlich aber hart im Ton', 'Wir haben keins', 'Nicht so gut', 'Wir sind beraten, installieren und konfigurieren die besten Solarzellen', 'Sehr druckvoll, aber auch liebevoll. Wir sind die Besten mit Herz und Seele.']

我的问题:

现在,答案列表会附加在每个响应的每个迭代中。但是,我想在每次响应后停止附加。

我想要的输出:

Response 1 :
    Response ID: 5rjqwlrxzzcve5s7ip05rjqw531fyk9q
    User's E-Mail Adress: philipp@ganster.com
    Answers : ['Asdflasdfjkasdf', 'ASdflasdfkö']
    
    
    Response 2 :
    Response ID: mnpxvbgbmgi0aut64g7mnpxvb1a66lb1
    User's E-Mail Adress: cool@cool.de
    Answers : ['Alles cool', 'Cool cooli cooli']
    
    
    Response 3 :
    Response ID: v2szjmf3by92rzpcyt6gxzv2szjmf3gj
    User's E-Mail Adress: elisa@andyduke.com
    Answers : ['Wir sind die Besten weltweit', 'Sehr freundlich aber hart im Ton']
    
    
    Response 4 :
    Response ID: 9nquhgyp7dtddqxzj8mg9nquh5tsernm
    User's E-Mail Adress: ganster95@gmail.com
    Answers : ['Wir haben keins', 'Nicht so gut']
    
    
    Response 5 :
    Response ID: 6y29hqnt2kr3nwtun6y292j5ede7kluc
    User's E-Mail Adress: philipp.ganster95@gmail.com
    Answers : ['Wir sind beraten, installieren und konfigurieren die besten Solarzellen', 'Sehr druckvoll, aber auch liebevoll. Wir sind die Besten mit Herz und Seele.']

谢谢您的帮助!

标签: pythonlistloopslist-comprehensionnested-loops

解决方案


如果dct问题中的字典是您的字典,您可以执行以下操作:

for i, d in enumerate(dct["items"], 1):
    print("Response {}:".format(i))
    print("Response ID: {}".format(d["response_id"]))
    print(
        "User's E-Mail Adress: {}".format(
            next(v for v in d["answers"] if v["type"] == "email")["email"]
        )
    )
    print("Answers: ", [v["text"] for v in d["answers"] if v["type"] == "text"])
    print()

印刷:

Response 1:
Response ID: 5rjqwlrxzzcve5s7ip05rjqw531fyk9q
User's E-Mail Adress: philipp@ganster.com
Answers:  ['Asdflasdfjkasdf', 'ASdflasdfkö']

Response 2:
Response ID: mnpxvbgbmgi0aut64g7mnpxvb1a66lb1
User's E-Mail Adress: cool@cool.de
Answers:  ['Alles cool', 'Cool cooli cooli']

Response 3:
Response ID: v2szjmf3by92rzpcyt6gxzv2szjmf3gj
User's E-Mail Adress: elisa@andyduke.com
Answers:  ['Wir sind die Besten weltweit', 'Sehr freundlich aber hart im Ton']

Response 4:
Response ID: 9nquhgyp7dtddqxzj8mg9nquh5tsernm
User's E-Mail Adress: ganster95@gmail.com
Answers:  ['Wir haben keins', 'Nicht so gut']

Response 5:
Response ID: 6y29hqnt2kr3nwtun6y292j5ede7kluc
User's E-Mail Adress: philipp.ganster95@gmail.com
Answers:  ['Wir sind beraten, installieren und konfigurieren die besten Solarzellen', 'Sehr druckvoll, aber auch liebevoll. Wir sind die Besten mit Herz und Seele.']


编辑:如果你有一个列表lst

for i, d in enumerate(lst, 1):
    print("Response {}:".format(i))
    print("Response ID: {}".format(d["response_id"]))
    print(
        "User's E-Mail Adress: {}".format(
            next(v for v in d["answers"] if v["type"] == "email")["email"]
        )
    )
    print("Answers: ", [v["text"] for v in d["answers"] if v["type"] == "text"])
    print()

推荐阅读