简体   繁体   English

当两个列表都基于索引匹配时,如何解码列表并从两个列表中删除项目?

[英]How to decode a list and remove items from two lists when there is a match in both of them based on an index?

I have two lists which contain the following type of information.我有两个列表,其中包含以下类型的信息。

List #1:
Request_List = ["1/1/1.34", "1/2/1.3.5", "1/3/1.2.3", ...same format elements]
List #2:
Reply_List = ["1/1/0", "1/3/1", "1/2/0", ...same format elements]

From the "Reply" list, I want to be able to compare the second item in the "#/#/#", in this case it will be 1,3,2, and so on with all the items in the Reply list and check if there is a match with the second item in "Request list".从“回复”列表中,我希望能够比较“#/#/#”中的第二项,在这种情况下它将是 1、3、2,依此类推与回复列表中的所有项目并检查是否与“请求列表”中的第二项匹配。 If there is a match, then I want to be able to return a new list which would contain the information of the third index in the request string appended with the third index of the matching string in the reply.如果有匹配项,那么我希望能够返回一个新列表,该列表将包含请求字符串中第三个索引的信息,并在回复中附加匹配字符串的第三个索引。

The result would be like the following. 
Result = ["1.34.0", "1.3.5.0", "1.2.3.1"] 

Note that the 0 was appended to the 1.34, the 1 was appended to the 1.3.4 and the 0 was appended to the 1.2.3 from the corresponding indexes in the "Reply" list as the second index existed in the "Reply" list.请注意,0 附加到 1.34,1 附加到 1.3.4,0 附加到 1.2.3 从“答复”列表中的相应索引,因为“答复”列表中存在第二个索引. The 'Reply" list could have the item anywhere placed in the list. “回复”列表可以将项目放置在列表中的任何位置。

The code which does the problem stated above is shown below.解决上述问题的代码如下所示。

def get_list_of_error_codes(self, Reply_List , Request_List ):
        decoded_Reply_List = Reply_List .decode("utf-8")  # I am not sure if this is 
                                           the right way to decode all the elements in the list? 

        Result = [
            f"{i.split('/')[-1]}.{j.split('/')[-1]}"
            for i in Request_List 
            for j in decoded_Reply_List
            if (i.split("/")[1] == j.split("/")[1])
        ]
        return Result
res = get_list_of_error_codes(Reply_List , Request_List)
print (res) # ["1.34.0", "1.3.5.0", "1.2.3.1"] 

Issues I am facing right now:我现在面临的问题:

  1. I am NOT sure if I decode the Reply_List correctly and in the proper manner.我不确定我是否以正确的方式正确解码了Reply_List Can someone help me also verify this?有人可以帮我验证一下吗?

  2. I am not sure on how to also remove the corresponding items for the Reply_List and Request_List when I find a match based on the condition if (i.split("/")[1] == j.split("/")[1]) .当我根据条件 if ( Reply_List if (i.split("/")[1] == j.split("/")[1]) Request_List if (i.split("/")[1] == j.split("/")[1])

  1. You can use list comprehension to decode the list:您可以使用列表推导来解码列表:

decoded_Reply_List = [li.decode(encoding='utf-8') for li in Reply_List]

  1. In this case, if you wanted to also remove items from the list while you create the new list, I would say list comprehension isn't the right move.在这种情况下,如果您还想在创建新列表时从列表中删除项目,我会说列表理解不是正确的举动。 Just go with the nested for loops:只需 go 与嵌套 for 循环:
def get_list_of_error_codes(self, Reply_List, Request_List):
    decoded_Reply_List = [li.decode(encoding='utf-8') for li in Reply_List]

    Result = []
    for i in list(Request_List):
        for j in decoded_Reply_List:
            if (i.split("/")[1] == j.split("/")[1]):
                Result.append(f"{i.split('/')[-1]}.{j.split('/')[-1]}")
                Reply_List.remove(j)
                break
        else:
            continue
        Request_List.remove(i)
    return Result

Request_List = ["1/1/1.34", "1/2/1.3.5", "1/3/1.2.3"]
Reply_List = [b"1/1/0", b"1/3/1", b"1/2/0"]
print(get_list_of_error_codes("Foo", Reply_List, Request_List))

# Output: ['1.34.0', '1.3.5.0', '1.2.3.1']            

Some things to note: I added a break so that we don't keep looking for matches if we find one.需要注意的一些事项:我添加了一个break ,这样我们就不会在找到匹配项时继续寻找匹配项。 It will only match the first pair, then move on.它只会匹配第一对,然后继续。

In for i in list(Request_List) , I added the list() cast to effectively make a copy of the list.for i in list(Request_List)中,我添加了list()强制转换以有效地制作列表的副本。 This allows us to remove entries from Request_List without disrupting the loop.这允许我们在不中断循环的情况下从Request_List中删除条目。 I didn't do this for for j in decoded_Reply_List because it's already a copy of Reply_List .我没有for j in decoded_Reply_List执行此操作,因为它已经是Reply_List的副本。 (I assumed you wanted to remove the entries from Reply_List ) (我假设您想从Reply_List中删除条目)

The last is the else: continue .最后一个是else: continue We don't want to reach Request_List.remove(i) if we didn't find a match.如果我们没有找到匹配项,我们不想到达Request_List.remove(i) If break is called, else will not be called, which means we will reach Request_List.remove(i) .如果调用了break ,则不会调用else ,这意味着我们将到达Request_List.remove(i) But if the loop completes without finding a match, the loop will then enter else and we will skip the removal step by calling continue但是如果循环完成但没有找到匹配项,则循环将进入else ,我们将通过调用continue跳过删除步骤

EDIT:编辑:

Actually, Reply_List.remove(j) breaks, since we've decoded j in this method, thus decoded j is not the same object as it is in Reply_List .实际上, Reply_List.remove(j)中断,因为我们已经在此方法中解码了j ,因此解码的j与 Reply_List 中的Reply_List Here's some revised code which will solve this issue:这里有一些修改后的代码可以解决这个问题:

def get_list_of_error_codes(Reply_List, Request_List):
    # decoded_Reply_List = [li.decode(encoding='utf-8') for li in Reply_List]

    Result = []
    for i in list(Request_List):
        for j in list(Reply_List):
            dj = j.decode(encoding='utf-8')
            if (i.split("/")[1] == dj.split("/")[1]):
                Result.append(f"{i.split('/')[-1]}.{dj.split('/')[-1]}")
                Reply_List.remove(j)
                break
        else:
            continue
        Request_List.remove(i)
    return Result

Request_List = ["1/1/1.34", "1/2/1.3.5", "1/3/1.2.3"]
Reply_List = [b"1/1/0", b"1/3/1", b"1/2/0"]
print("Result: ", get_list_of_error_codes(Reply_List, Request_List))
print("Reply_List: ", Reply_List)
print("Request_List: ", Request_List)

# Output:
# Result:  ['1.34.0', '1.3.5.0', '1.2.3.1']
# Reply_List:  []
# Request_List:  []

What I've done is that instead of creating a separate decoded list, I just decode the entries as they're looped through, and then remove the un-decoded entry from Reply_List .我所做的是,我没有创建单独的解码列表,而是在条目循环时对其进行解码,然后从Reply_List中删除未解码的条目。 This should be a little more efficient too, since we're not looping through Reply_List twice now.这也应该更有效一些,因为我们现在没有循环两次Reply_List

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据任一索引中的值从两个列表中删除项目 - Remove items from two lists based on value at index in either 从列表中删除不匹配两个列表的项目 - Remove items from lists that doesn't match two lists 当两个列表组合在一起时如何从列表项中删除括号、逗号和引号 - How to remove parenthesis, commas, and quotation marks from list items when two lists are combined together 两个带有相应编号的单独列表。 如何检测到它们从列表中删除? - Two separate lists with corresponding numbers. How to detect them remove them from the list? 如何匹配两个不同列表中的项目并根据 python 中的匹配项创建新列表? - How to match items in two different lists and create a new list based on the matches in python? 如何使用Pandas选择两列项与两个列表项(相同索引)匹配的行? - How to select rows where items of two columns match with items of two lists (same index), using Pandas? 我如何从两个列表中选择一个随机项目,然后从所有可能性中建立的另一个列表中删除该项目集 - How can i select random items from a set of two lists and then remove that set of items from another list built out of all the possibilities 如何制作两个列表并根据另一个列表删除元素? - how to make take two lists and remove elements based on another list? 如何从较大列表中的较小列表中删除项目? - How to remove items from smaller lists that are in a larger list? 从两个列表中删除两个集合列表的交集,并将 append 它添加到 python 中的新列表 - Remove the intersection of two list of sets from both lists, and append it to a new list in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM