首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用列表中的确切值搜索另一个列表。添加带有搜索结果的变量

使用列表中的确切值搜索另一个列表。添加带有搜索结果的变量
EN

Stack Overflow用户
提问于 2019-07-05 14:29:05
回答 2查看 52关注 0票数 0

我需要创建一个list/dataframe,其中包含组件ID和它们的描述。我有一个包含组件ID的列表和另一个包含有描述的组件ID的列表。只应在两个列表中显示ID的组件及其说明。

我尝试使用组件ID列表来精确搜索组件和描述列表。我没能得到想要的输出。

代码语言:javascript
复制
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中才会有循环。

我希望输出的内容如下:

代码语言:javascript
复制
R402 , MSG ='4k2 1%'

这将要求我删除描述列表中等号之前的所有内容。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-07-05 16:16:43

这是一种简单(容易理解)的方式来完成你所需要的!

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
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']

我已经更改了您的描述和组件列表,以涵盖您可能面临的所有场景。此外,描述列表在每个元素中都有额外的引号。如果要将这些引号保留在列表中,则必须使用转义字符

在组合列表中,如果要删除等于签名(在描述列表中)之前的所有内容,请使用以下任何一项(取决于描述列表中的所有元素)。

代码语言:javascript
复制
desclist[j].split('=',1)[1]
desclist[j].rpartition('=')[2]
票数 0
EN

Stack Overflow用户

发布于 2019-07-05 14:39:46

尝尝这个,

代码语言:javascript
复制
>>> 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']

输出:

代码语言:javascript
复制
>>> 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%"']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56905008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档