Skip to main content
 首页 » 编程设计

python之过滤掉不在组件列表中的描述

2025年05月04日19Renyi-Fan

我有 2 个列表,一个有很多组件,另一个有组件及其描述。我需要找到一种方法来过滤掉所有无用的信息,同时保持描述列表的顺序与组件列表的顺序相同。

我曾尝试使用列表理解,但这并没有给我预期的结果。

lst = []  
for i in range (len(components)): 
   lst.append([x for x in description if components[i] in x]) 

这是两个变量的简短版本;

components = ['INVALID' , 'R100' , 'R101' , 'C100' , 'R100' , 'R100'] 
description = [ 
'  30_F "30_F";', 
'  POWER_IN1 Supply   2 At     5 Volts, 0.8 Amps;', 
'  R100       OPEN PN"10057609" "RES S 5mOhm 1% 2512_H6_1(T)";', 
'  R101          100     5     5 f PN"66151002538" "CH-WID_ 100R -5-RR 0603 (B)";', 
'  C100          100n    10    10 f PN"10210616" "CFCAP X7R S 100nF 50V (T)";', 
'  R100       OPEN PN"10057609" "RES S 5mOhm 1% 2512_H6_1(T)";', 
'  R100       CLOSED PN"10057609" "RES S 5mOhm 1% 2512_H6_1 (T)"      VERSION 12046547;'] 

我期望的输出是;

'  INVALID    No description' 
'  R100       OPEN PN"10057609" "RES S 5mOhm 1% 2512_H6_1(T)";' 
'  R101       100     5     5 f PN"66151002538" "CH-WID_ 100R -5-RR 0603 (B)";' 
'  C100       100n    10    10 f PN"10210616" "CFCAP X7R S 100nF 50V (T)";' 
'  R100       OPEN PN"10057609" "RES S 5mOhm 1% 2512_H6_1(T)";' 
'  R100       CLOSED PN"10057609" "RES S 5mOhm 1% 2512_H6_1 (T)"      VERSION 12046547; 

请您参考如下方法:

利用str.startswith函数,辅助seen positions序列和Python的for/else特性:

import pprint 
 
...  # your input data variables 
 
seen_pos = [] 
res = [] 
for comp in components: 
    for i, desc in enumerate(description): 
        if i not in seen_pos and desc.strip().startswith(comp): 
            seen_pos.append(i) 
            res.append('{:<10}{}'.format(comp, desc.strip().replace(comp, '', 1).strip())) 
            break 
    else: 
        res.append('{:<10}{}'.format(comp, 'No description')) 
 
pprint.pprint(res, width=100) 

输出:

['INVALID   No description', 
 'R100      OPEN PN"10057609" "RES S 5mOhm 1% 2512_H6_1(T)";', 
 'R101      100     5     5 f PN"66151002538" "CH-WID_ 100R -5-RR 0603 (B)";', 
 'C100      100n    10    10 f PN"10210616" "CFCAP X7R S 100nF 50V (T)";', 
 'R100      OPEN PN"10057609" "RES S 5mOhm 1% 2512_H6_1(T)";', 
 'R100      CLOSED PN"10057609" "RES S 5mOhm 1% 2512_H6_1 (T)"      VERSION 12046547;']