[英]Move multiple elements (based on criteria) to end of list
I have the following 2 Python lists: 我有以下2个Python列表:
main_l = ['Temp_Farh', 'Surface', 'Heater_back', 'Front_Press',
'Lateral_Cels', 'Gauge_Finl','Gauge_Relay','Temp_Throw','Front_JL']
hlig = ['Temp', 'Lateral', 'Heater','Front']
I need to move elements from main_l
to the end of the list if they contain strings listed in hlig
. 如果元素包含
hlig
列出的字符串,则需要将它们从main_l
移到列表的hlig
。
Final version of main_l
should look like this: main_l
最终版本应如下所示:
main_l = ['Surface', 'Gauge_Finl','Gauge_Relay', 'Temp_Farh', 'Heater_back', 'Front_Press',
'Lateral_Cels', 'Temp_Throw','Front_JL']
My attempt: 我的尝试:
I first try to find if the list main_l
contains elements with a substring listed in the 2nd list hlig
. 我首先尝试查找列表
main_l
包含具有在第二个列表hlig
列出的子字符串的元素。 Here is the way I am doing this: 这是我这样做的方式:
`found` = [i for e in hlig for i in main_l if e in i]
found
is a sublist of main_l
. found
是main_l
的子列表。 The problem is: now that I have this list, I do not know how to select the elements that do NOT contain the substrings in hlig
. 问题是:现在有了这个列表,我不知道如何选择不包含
hlig
的子字符串的hlig
。 If I could do this, then I could add them to a list not_found
and then I could concatenate them like this: not_found + found
- and this would give me what I want. 如果我可以这样做,则可以将它们添加到列表
not_found
,然后将它们连接起来: not_found + found
这样就可以得到我想要的东西。
Question: 题:
Is there a way to move matching elements to end of the list main_l
? 有没有办法将匹配的元素移动到列表
main_l
?
您可以使用每个元素是否包含来自hlig的字符串作为键来对main_l
进行排序:
main_l.sort(key=lambda x: any(term in x for term in hlig))
I would rewrite what you have to: 我将重写您必须执行的操作:
main_l = ['Temp_Farh', 'Surface', 'Heater_back', 'Front_Press', 'Lateral_Cels', 'Gauge_Finl','Gauge_Relay','Temp_Throw','Front_JL']
hlig = ['Temp', 'Lateral', 'Heater','Front']
found = [i for i in main_l if any(e in i for e in hlig)]
Then the solution is obvious: 那么解决方案显而易见:
not_found = [i for i in main_l if not any(e in i for e in hlig)]
answer = not_found + found
EDIT: Removed square brackets around list comprehension based on comments by Sven Marnach (to aviraldg's solution) 编辑:根据Sven Marnach(对aviraldg的解决方案)的评论,删除了列表理解周围的方括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.