python - 如何提取嵌套在dict列表中的值列表?
问题描述
这是一个示例代码:
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()
:
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
和Douglas Lyphe and Jackson Pot
。
推荐阅读
- ruby-on-rails - RSpec 没有路线匹配 {:action=>"/dashboard/sites/24/attendance_summer_city_camp_integrativ.xlsx", :controller=>"dashboard/sites"}
- reactjs - 从子组件触发 onClick 函数
- java - Java中线程的空闲时间是什么意思?
- javascript - 获取对象本身内部的数组内部对象的值
- c# - 为什么我的 EditorFor 日期选择器字段没有填充我的值?
- c++ - 如何在 C++ 中制作十进制随机数生成器?
- symfony - 如何使用 TerserPlugin 和 webpack-encore 进行缩小
- c++ - C++ g_signal_connect实现gtkmm,返回警告
- javascript - 跟踪由 react-window 渲染的项目的可见性
- excel - 如何从单元格中提取字符串中的前两个字符并打印到另一个单元格