将dict列表转换为字符串

2024-09-24 02:16:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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

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

有什么建议吗?


Tags: 字符串comtrue列表exampleuser口述陌生
3条回答

这些单句没问题,但初学者可能听不懂。它们在这里被分解:

list_of_dicts = (the list you posted)

好的,我们有一个列表,每个成员都是一个dict

[expr for d in list_of_dicts]

这就像说for d in list_of_dicts ...expr为每个d求值,并生成一个新列表。你也可以用if选择其中的一些,参见文档。

那么,我们想要什么?在每个dictd中,我们需要与键'memberId'一起的值。那是d['memberId']。因此,现在列表的理解是:

[d['memberId'] for d in list_of_dicts]

这给了我们一个电子邮件地址列表,现在要将它们与逗号放在一起,我们使用join(参见文档):

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

我看到其他的海报把join的参数列表中的[]去掉了,它就工作了。我不知道你为什么不查。哦。

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

既然你说你是Python新手,我将解释这是如何工作的。

^{}方法组合iterable的每个元素(如列表),并使用方法调用的字符串作为分隔符。

提供给方法的iterable是生成器表达式(d['memberId'] for d in my_list)。这实际上给了您列表理解创建的列表中的每个元素[d['memberId'] for d in my_list],而不实际创建列表。

听录音。

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

相关问题 更多 >