【问题标题】:Looping through list of lists in Python [closed]循环遍历Python中的列表列表[关闭]
【发布时间】:2023-03-09 06:57:02
【问题描述】:

我正在尝试遍历 Python 中的列表列表,但在每次循环迭代中我只得到相同的列表(即第一条记录)。

def append_dict(result):
    for row in result:
        fruit = row[0]
        color = row[1]
        email = row[2]
        
        dict_data = {
            'fruit' : fruit,
            'color' : color,
            'email' : email
        }
        return dict_data

thislist = [["apple", "red", "xyz@abc.com"],["banana", "blue", "abc@xyz.com"]]
for i in range(len(thislist)):
  load = append_dict(thislist)
  print(load)

结果:

{'fruit': 'apple', 'color': 'red', 'email': 'xyz@abc.com'}
{'fruit': 'apple', 'color': 'red', 'email': 'xyz@abc.com'}

预期结果:

{'fruit': 'apple', 'color': 'red', 'email': 'xyz@abc.com'}
{'fruit': 'banana', 'color': 'blue', 'email': 'abc@xyz.com'}

【问题讨论】:

  • 你的循环变量被称为i,你永远不会在任何地方使用它。

标签: python-3.x list


【解决方案1】:

这里有两个不同的问题:

  1. 您的append_dict 函数尝试遍历整个列表列表,但它只返回第一行。
  2. 您的最终 for 循环循环遍历整个列表列表,但它每次都做同样的事情(将整个列表传递给 append_dict,而 append_dict 又只对第一行进行操作)。

我建议让append_dict 只在一行上运行,而让你的另一个for 循环遍历这些行:

def append_dict(row: list) -> dict:
    fruit = row[0]
    color = row[1]
    email = row[2]
        
    dict_data = {
        'fruit' : fruit,
        'color' : color,
        'email' : email
    }
    return dict_data


thislist = [["apple", "red", "xyz@abc.com"],["banana", "blue", "abc@xyz.com"]]
for row in thislist:
    load = append_dict(row)
    print(load)

您还可以编写函数以将所有字典作为列表返回:

from typing import Dict, List

def build_dicts(result: List[List[str]]) -> List[Dict[str, str]]:
    return [{
        'fruit': fruit,
        'color': color,
        'email': email,
    } for [fruit, color, email] in result]


thislist = [["apple", "red", "xyz@abc.com"],["banana", "blue", "abc@xyz.com"]]
for load in build_dicts(thislist):
    print(load)

【讨论】:

    猜你喜欢
    • 2018-10-26
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多