[英]Python: Remove list item if it is key for a given value from dictionary
I have a function h()
that returns a tuple corresponding to the most common element in a list and its value from a dictionary called " Values
" - so for example, if the most common element in list1
is a string "test"
that occurs three times and that corresponds to Values = {"test":10}
, then h(list1) = [3,10]
. 我有一个函数h()
,该函数返回一个与列表中最常见元素相对应的元组,并从名为“ Values
”的字典中返回其值-例如,如果list1
最常见的元素是出现的字符串"test"
三遍,对应于Values = {"test":10}
,然后h(list1) = [3,10]
。
When two lists share the same element/frequency, I want to remove the most common element. 当两个列表共享相同的元素/频率时,我想删除最常见的元素。 Here is what I'm trying: 这是我正在尝试的:
list1.remove([k for k,v in Values.items() if v == h(list1)[1]])
ValueError: list.remove(x): x not in list
How can I remove the key from a list based on its value in the Values
dictionary? 如何根据“ Values
字典中的Values
从列表中删除键?
Remove only expects a single element. 删除仅需要单个元素。
toremove = {k for k,v in Values.items() if v == h(list1)[1]]}
#either:
for r in toremove:
list1.remove(r)
#or (less efficient)
list1 = = [i for i in list1 if i not in toremove]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.