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'})]
>>>
添加回答
舉報