我有以下 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']
如果元素包含 hlig 中列出的字符串,我需要将元素从 main_l 移动到列表的末尾。
main_l 的最终版本应该如下所示:
main_l = ['Surface', 'Gauge_Finl','Gauge_Relay', 'Temp_Farh', 'Heater_back', 'Front_Press',
'Lateral_Cels', 'Temp_Throw','Front_JL']
我的尝试:
我首先尝试查找列表 main_l 是否包含具有第二个列表 hlig 中列出的子字符串的元素。这是我这样做的方式:
`found` = [i for e in hlig for i in main_l if e in i]
found 是 main_l 的子列表。问题是:现在有了这个列表,我不知道如何选择不包含 hlig 中的子字符串的元素。如果我能做到这一点,那么我可以将它们添加到列表 not_found 中,然后我可以像这样连接它们:not_found + found - 这会给我我想要的.
问题:
有没有办法将匹配元素移动到列表 main_l 的末尾?
请您参考如下方法:
您可以使用每个元素是否包含来自 hlig 的字符串作为键来对 main_l 进行排序:
main_l.sort(key=lambda x: any(term in x for term in hlig))
