簡體   English   中英

如何提取兩個不同嵌套列表中相同元素的子列表信息並存儲?

[英]How to extract sub-list information of identical elements in two different nested lists and storing them?

我正在為以下內容尋求您的幫助,我是 Python 新手。 先感謝您。

我有 2 個示例嵌套列表:

list1 = [['*1', '*2'], ['*3', '*4'], ['*5', '*6', '+1', '+4'], ['+2', '+5', '+3']]

list2 = [['*2', '*6', '*1', '+4', '*4'], ['*3', '*5', '+3', '+5'], ['+1'], ['+2']]

兩個嵌套列表具有相同的字符串元素,但位於不同的子列表中。

對於兩個嵌套列表中的每個元素,我需要:

  1. 查找它在 list1 中出現的子列表編號。 例如, list1'*1'在子列表 1 中,列表list1'*6'在子列表 3 中,以此類推所有元素。 所以我需要創建一個字典,其中每個字符串元素作為鍵, list1中的子列表編號作為值。
Desired Output:
list1_location = {'*1': '1', '*2': '1', '*3': '2', '*4': '2', '*5': '3', '*6': '3', '+1': '3', '+4': '3', '+2': '4', '+5': '4', '+3': '4'}
  1. 查找它在 list2 中出現的子列表編號。 例如, list2'*5'在子列表 2 中,列表list2'+2'在子列表 4 中,以此類推所有元素。 所以我需要創建一個字典,其中每個字符串元素作為鍵, list2中的子列表編號作為值。
Desired Output:
list2_location = {'*2': '1', '*6': '1', '*1': '1', '+4': '1', '*4': '1', '*3': '2', '*5': '2', '+3': '2', '+5': '2', '+1': '3', '+2': '4'}
  1. 根據列表 1 和列表 2 中的子列表位置找到每個元素的 (difference + 1)。 例如, list1中的'*1'位於子列表 1 中,而list2'*1'位於子列表 1 中。因此,(list1 - list2 + 1)= (1-1+1)= 1。類似地, '*6'list1中位於子列表 3 中,而'*6'list2中位於子列表 1 中。所以,(list1 - list2 + 1)= (3-1+1)= 3。所以我需要用這些中的每一個創建一個字典字符串元素作為鍵,差值(list1 - list2 + 1)作為值。
Desired Output:
diff_dict = {'*1': '1', '*2': '1', '*3': '1', '+1': '1', '+2': '1', '*4': '2', '*5': '2', '*6': '3', '+3': '3', '+4': '3', '+5': '3'}

我正在嘗試以下操作:

list1 = [['*1', '*2'], ['*3', '*4'], ['*5', '*6', '+1', '+4'], ['+2', '+5', '+3']]
list2 = [['*2', '*6', '*1', '+4', '*4'], ['*3', '*5', '+3', '+5'], ['+1'], ['+2']]
new_list = []
for i in list1:
        for j in list2:
            if i[0] == j[0]:
                 new_list.append(j)
print(new_list)

def index_tracker(list_):
    return {item : i + 1 for i, sub_list in enumerate(list_) for item in sub_list}

list1_location = index_tracker(list1)
list2_location = index_tracker(list2)

diff_dict = {k: str(v - list2_location[k] + 1) for k, v in list1_location.items()}

>>> print(diff_dict)
>>> {'*1': '1', '*2': '1', '*3': '1', '*4': '2', '*5': '2', '*6': '3', '+1': '1', '+4': '3', '+2': '1', '+5': '3', '+3': '3'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM