gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:38 24 4
gpt4 key购买 nike

我有 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;']

关于python - 过滤掉不在组件列表中的描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57510950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com