获取元组列表并根据每个元组中的第一个数字将它分成单独的列表。在同一步骤中,使用从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()
像
len([x for x in list2[0] if x[0] == i+1])
这一变化后,d
将包含长度,而不是数据:
print(d) //{'A': 4, 'B': 4}
看在'split()',列表解析,'len()'和'dict'构造函数中。 – 2012-07-30 17:19:31
确定如何对字符串中的项目进行分组的规则究竟是什么?如果有12对而不是8对,是两个4或6中的3个?或者它是将它切成足够的块与list1一起使用? – 2012-07-30 17:19:59
如果1,1或1,2的第一个元素是1,那么它应该保存在sublist1中,否则如果第一个元素2,1或2,2或2,3是2,那么它应该保存在sublist2中。 – smazon09 2012-07-30 17:23:21