我需要创建一个list/dataframe,其中包含组件ID和它们的描述。我有一个包含组件ID的列表和另一个包含有描述的组件ID的列表。只应在两个列表中显示ID的组件及其说明。
我尝试使用组件ID列表来精确搜索组件和描述列表。我没能得到想要的输出。
desclist = ['R402 MSG ='4k2 1%'','R403 MSG ='100 1%'','R404 MSG ='4k 1%'']
component = ['R402','R403','R404']
combinedlist = []
while count<(len(component) - 1):
while True:
for c in desclist:
if c in component[count]:
combinedlist.append(c)
print(comp[count]+ ' , ' + desclist[count])
count = count + 1 这不是我尝试过的代码,但相信这与我所需要的类似,我知道只有在python中才会有循环。
我希望输出的内容如下:
R402 , MSG ='4k2 1%'这将要求我删除描述列表中等号之前的所有内容。
发布于 2019-07-05 16:16:43
这是一种简单(容易理解)的方式来完成你所需要的!
desclist = ['R402 MSG = Desc402','R403 MSG = Desc403',
'R404 MSG = Desc404','R405 MSG = Desc405']
component = ['R402','R403','R404','R406']
combinedlist = []
for i in range(len(component)):
found = False
for j in range(len(desclist)):
if str(component[i]) == str(desclist[j]).split(' ')[0]:
found = True
combinedlist.append(component[i] + ', ' + desclist[j].split(' ',1)[1])
print(component[i], ',', desclist[j].split(' ',1)[1])
#print('Comp : ', component[i], 'Desc : ', desclist[j].split(' ',1)[1])
break
if not found:
print(component[i], ' not found in Description List')
print('Combined List : ', combinedlist)输出:
R402 , MSG = Desc402
R403 , MSG = Desc403
R404 , MSG = Desc404
R406 not found in Description List
Combined List : ['R402, MSG = Desc402', 'R403, MSG = Desc403', 'R404, MSG = Desc404']我已经更改了您的描述和组件列表,以涵盖您可能面临的所有场景。此外,描述列表在每个元素中都有额外的引号。如果要将这些引号保留在列表中,则必须使用转义字符。
在组合列表中,如果要删除等于签名(在描述列表中)之前的所有内容,请使用以下任何一项(取决于描述列表中的所有元素)。
desclist[j].split('=',1)[1]
desclist[j].rpartition('=')[2]发布于 2019-07-05 14:39:46
尝尝这个,
>>> desclist = ['R402 MSG = "4k2 1%"','R403 MSG ="100 1%"','R404 MSG ="4k 1%"', 'R407 MSG ="4k 1%"']
# For test i have added 'R407 MSG ="4k 1%"'
>>> component = ['R402','R403','R404']输出:
>>> from itertools import chain
>>> new_list = [[desc for desc in desclist if cid in desc] for cid in component]
>>> list(chain(*new_list))
['R402 MSG = "4k2 1%"', 'R403 MSG ="100 1%"', 'R404 MSG ="4k 1%"']https://stackoverflow.com/questions/56905008
复制相似问题