【问题标题】:Use exact value from a list to search another list. Append variable with results from search使用列表中的确切值来搜索另一个列表。使用搜索结果附加变量
【发布时间】:2019-11-16 04:52:29
【问题描述】:

我需要创建一个列表/数据框,其中包含组件 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%'

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

【问题讨论】:

  • desclist 引号有问题,你可以解决它
  • 您的预期输出应该包含所有值,因为它们的 ID 存在于 component 中,对吧?
  • 但 R403 和 R404 也在两个列表中。为什么它们不在预期的输出中?

标签: python loops search


【解决方案1】:

试试这个,

>>> 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%"']

【讨论】:

  • 您好,我在程序“列表索引超出范围”中遇到错误。组件 ID 列表有大约 1300 个值,描述一个有大约 2500 个。有些描述没有组件 ID,甚至只是空白,我不确定这是否是问题所在。
  • @mark7378 我使用chain 来展平列表。所以,它不应该创建列表列表。
【解决方案2】:

这是完成您需要的简单(易于理解)的方法!

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']

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

在您的组合列表中,如果您想删除等号之前的所有内容(在描述列表中),请使用以下任意一种(取决于描述列表中的所有元素)。

desclist[j].split('=',1)[1]
desclist[j].rpartition('=')[2]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 2022-01-21
    • 2012-09-06
    相关资源
    最近更新 更多