3 回答

TA贡献1859条经验 获得超6个赞
在您的列表理解中,i
是元组之一,所以('John', 'Samantha', {'source': 'family'})
或('John', 'Jill', {'source': 'work'})
。那不是字典,所以你不能像字典一样对待它!
如果您的元组始终由3个元素组成,而第3个元素是带source
键的字典,请使用:
[i for i in my_list if i[2]['source'] == 'family']
如果这些假设中的任何一个都不成立,则必须添加更多代码。例如,如果字典始终在那儿,但是'source'
键可能丢失了,那么dict.get()
当键不在那儿时,您可以使用它来返回默认值:
[i for i in my_list if i[2].get('source') == 'family']
如果元组的长度可以变化,但是字典始终是最后一个元素,则可以使用负索引:
[i for i in my_list if i[-1]['source'] == 'family']
等。作为程序员,您始终必须检查这些假设。

TA贡献1839条经验 获得超15个赞
我建议您基于理解,采用以下解决方案,仅假设字典中始终有一个名为“源”的键,如您在评论中所述:
my_list = [('John', 'Samantha', {'source': 'family'}),
('John', 'Jill', {'source': 'work'}),
('Mary', 'Joseph', {'source': 'family'})]
# Keep only elements including a dictionary with key = "source" and value = "family"
my_filtered_list = [t for t in my_list if any((isinstance(i,dict) and i['source'] == 'family') for i in t)]
print(my_filtered_list) # [('John', 'Samantha', {'source': 'family'}), ('Mary', 'Joseph', {'source': 'family'})]
# If needed: remove the dictionary from the remaining elements
my_filtered_list = [tuple(i for i in t if not isinstance(i,dict)) for t in my_filtered_list]
print(my_filtered_list) # [('John', 'Samantha'), ('Mary', 'Joseph')]

TA贡献1836条经验 获得超3个赞
您可以使用过滤器功能过滤列表
>>> li = [('John', 'Samantha', {'source': 'family'}),
... ('John', 'Jill', {'source': 'work'})]
>>>
>>> filtered = list(filter(lambda x: x[2]['source'] == 'family', li))
>>>
>>> filtered
[('John', 'Samantha', {'source': 'family'})]
>>>
添加回答
举报