我对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。
有什么建议吗?
这些单句没问题,但初学者可能听不懂。它们在这里被分解:
好的,我们有一个列表,每个成员都是一个dict
这就像说
for d in list_of_dicts ...
。expr
为每个d求值,并生成一个新列表。你也可以用if
选择其中的一些,参见文档。那么,我们想要什么?在每个dict
d
中,我们需要与键'memberId'
一起的值。那是d['memberId']
。因此,现在列表的理解是:这给了我们一个电子邮件地址列表,现在要将它们与逗号放在一起,我们使用
join
(参见文档):我看到其他的海报把
join
的参数列表中的[]去掉了,它就工作了。我不知道你为什么不查。哦。既然你说你是Python新手,我将解释这是如何工作的。
^{} 方法组合iterable的每个元素(如列表),并使用方法调用的字符串作为分隔符。
提供给方法的iterable是生成器表达式
(d['memberId'] for d in my_list)
。这实际上给了您列表理解创建的列表中的每个元素[d['memberId'] for d in my_list]
,而不实际创建列表。听录音。
相关问题 更多 >
编程相关推荐