[英]How to create sub-lists with 3 elements, but if a sub-list gets a single element then instead create two with 2 elements?
[英]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']]
两个嵌套列表具有相同的字符串元素,但位于不同的子列表中。
对于两个嵌套列表中的每个元素,我需要:
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'}
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'}
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.