python:从嵌套列表中删除时保留某些值

python: preserve certain values when removing from a nested list

我有一个嵌套列表如下:

my_list = [['id_1', {'frame':[{'door': 'window', 'closet':'pinches'}], 'utterance':'sentence number 1', 'speaker':'silver'}],
 ['id_2',{'frame':[{'door': 'window', 'closet':'pinches'},{'door': 'new_door', 'closet':'hinges'}], 'utterance':'sentence number 2', 'speaker':'silver'}],
 ['id_3', {'frame':[{'door': 'window', 'closet':'pins'}], 'utterance':'sentence number 3', 'speaker':'gold'}]]

我想从 my_list 中删除一个列表,如果它包含值 'gold',所以我做了以下操作。

removed =[i for i in [item[1] for item in my_list] if not(i['speaker'] == 'gold')]

print(removed) 
#output: [{'frame': [{'door': 'window', 'closet': 'pinches'}], 'utterance': 'sentence number 1', 'speaker': 'silver'}, {'frame': [{'door': 'window', 'closet': 'pinches'}, {'door': 'new_door', 'closet': 'hinges'}], 'utterance': 'sentence number 2', 'speaker': 'silver'}]

但是我想保留'id_number',所以我想要的输出是:

my_new_list = [['id_1', {'frame':[{'door': 'window', 'closet':'pinches'}], 'utterance':'sentence number 1', 'speaker':'silver'}],
 ['id_2',{'frame':[{'door': 'window', 'closet':'pinches'},{'door': 'new_door', 'closet':'hinges'}], 'utterance':'sentence number 2', 'speaker':'silver'}]]

试试这个:

my_list = [['id_1', {'frame':[{'door': 'window', 'closet':'pinches'}], 'utterance':'sentence number 1', 'speaker':'silver'}],
 ['id_2',{'frame':[{'door': 'window', 'closet':'pinches'},{'door': 'new_door', 'closet':'hinges'}], 'utterance':'sentence number 2', 'speaker':'silver'}],
 ['id_3', {'frame':[{'door': 'window', 'closet':'pins'}], 'utterance':'sentence number 3', 'speaker':'gold'}]]
new_list = []
new_list.extend([i for i in my_list if i[1]['speaker'] != "gold" ])

我认为您只需要“切换”2 个内联循环:

removed =[item for item in my_list if not(item[1]['speaker'] == 'gold')]