gpt4 book ai didi

python - 将字典列表转换为字符串

转载 作者:太空狗 更新时间:2023-10-29 21:16:59 25 4
gpt4 key购买 nike

我是 Python 的新手,如果这比我想象的要容易,请原谅我。

我收到了一个字典列表,如下所示:

[{'directMember': 'true', 'memberType': 'User', 'memberId': 'address1@example.com'},  
{'directMember': 'true', 'memberType': 'User', 'memberId': 'address2@example.com'},
{'directMember': 'true', 'memberType': 'User', 'memberId': 'address3@example.com'}]

我想生成一个简单的 memberId 字符串,例如

address1@example.com, address2@example.com, address3@example.com

但是我尝试过的每一种将列表转换为字符串的方法都失败了,因为涉及到字典。

有什么建议吗?

最佳答案

', '.join(d['memberId'] for d in my_list)

既然您说您是 Python 的新手,那么我将解释它是如何工作的。

str.join()方法组合了一个可迭代对象(如列表)的每个元素,并使用调用该方法的字符串作为分隔符。

提供给该方法的可迭代对象是生成器表达式 (d['memberId'] for d in my_list)。这实质上为您提供了列表理解 [d['memberId'] for d in my_list] 创建的列表中的每个元素,而无需实际创建列表。

关于python - 将字典列表转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5253773/

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