gpt4 book ai didi

python - 如何提取嵌套在字典列表中的值列表?

转载 作者:行者123 更新时间:2023-12-01 07:56:00 24 4
gpt4 key购买 nike

这是一个示例代码:

list1 = [{'name': 'foobar', 'parents': ['John Doe', 'and', 'Bartholomew' 'Shoe'],
{'name': 'Wisteria Ravenclaw', 'parents': ['Douglas', 'Lyphe', 'and', 'Jackson', 'Pot']
}]

我需要获取父级的值并将它们作为字符串打印出来。示例输出:

John Doe and Bartholomew Shoe, Douglas Lyphe and Jackson Pot

我尝试过:

list2 = []

for i in list1:
if i['parents']:
list2.append(i['parents'])

然后,我尝试 join() 它们,但它们是嵌套在列表中的列表,因此,我还没有找到我正在寻找的解决方案。

有人可以帮我解决这个问题吗?

最佳答案

使用列表理解和join():

list1 = [{'name': 'foobar', 'parents': ['John Doe', 'and', 'Bartholomew', 'Shoe']},
{'name': 'Wisteria Ravenclaw', 'parents': ['Douglas', 'Lyphe', 'and', 'Jackson', 'Pot']}]

parents = ', '.join([' '.join(dic['parents']) for dic in list1])
print(parents)

输出:

John Doe and Bartholomew Shoe, Douglas Lyphe and Jackson Pot

内部 join() 组合每个名称列表中的元素(例如。['John Doe', 'and', 'Bartholomew', 'Shoe']变为 John Doe and Bartholomew Shoe),外部 join() 组合了列表理解产生的两个元素:John Doe and Bartholomew Shoe以及道格拉斯·莱夫和 jackson ·波特

关于python - 如何提取嵌套在字典列表中的值列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55982605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com