获取您的元组列表并根据每个元组中的第一个数字将其拆分为单独的列表。在同一步骤中,将过滤后的列表添加到具有相应键 from 的字典中list1
。由于list2
(复制如下)中的双括号,实际数据在list2[0]
.
//note the double brackets, data is in list2[0], not list2
list2 = [[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)]]
d = dict()
for i in range (0, len(list1)):
d[list1[i]] = [x for x in list2[0] if x[0] == i+1]
//on the first run though, list[i] will be 'A' and will be set to [(1, 1), (1, 2), (1, 3), (1, 4)]
//on the 2nd run though, list[i] will be 'B' and will be set to [(2, 1), (2, 2), (2, 3), (2, 4)]
打印d
显示格式化数据
print(d)
//prints {'A': [(1, 1), (1, 2), (1, 3), (1, 4)], 'B': [(2, 1), (2, 2), (2, 3), (2, 4)]}
编辑:我误读了这个问题(我以为你想要字典中的实际数据,而不仅仅是长度)。要获取列表的长度而不是内容,只需将第二个列表理解包装在len()
like
len([x for x in list2[0] if x[0] == i+1])
更改后,d
将包含长度,而不是数据:
print(d) //{'A': 4, 'B': 4}