def comparenumber(current, previous):
if current == previous:
return True
else:
return False
def getvalues():
sorted_list = [[8, 13], [8, 14], [8, 15], [8, 16], [8, 17], [9, 11], [9, 12], [9, 13], [9, 14], [9, 15], [9, 16], [9, 17], [9, 18], [10, 10], [10, 11], [10, 12], [10, 13], [10, 17], [10, 18], [11, 9], [11, 10], [11, 11], [11,17], [11, 18], [12, 8], [12, 9], [12, 10], [12, 16], [12, 17], [13, 7], [13, 8], [13, 9], [13, 16], [14, 7], [14, 8], [14, 15], [15, 7], [15, 8], [15, 13], [15, 14], [16, 8], [16, 9], [16, 10], [16, 11], [16, 12], [16, 13], [16, 14], [16, 15], [17, 14], [17, 15], [17, 16], [18, 15], [18, 16], [19, 15], [19, 16]]
count = 0
my_list = []
column_list = []
is_same = False
length = len(sorted_list)
while count < length:
current = sorted_list[count + 1][0]
previous = sorted_list[count + 1 - 1][0]
is_same = comparenumber(current, previous)
my_list.append(sorted_list[count][1])
if is_same == False:
column_list.append(my_list)
my_list = []
count = count + 1
print(column_list)
我需要比较第一个列表的第一个元素和下一个列表的第一个元素,如果它返回false。然后将其存储在另一个列表中。我在这里缺少什么?
我期望的输出是[13,14,15,16,17],[11,12,13,14,15,16,17,18],[10,11,12,13],17,18],….]
使用defaultdict(list(
from collections import defaultdict
d_dict = defaultdict(list)
for k,v in sorted_list:
d_dict[k].append(v)
print ( list( d_dict.values() ) )
输出:
[[13, 14, 15, 16, 17], [11, 12, 13, 14, 15, 16, 17, 18], [10, 11, 12, 13, 17, 18], [9, 10, 11, 17, 18], [8, 9, 10, 16, 17], [7, 8, 9, 16], [7, 8, 15], [7, 8, 13, 14], [8, 9, 10, 11, 12, 13, 14, 15], [14, 15, 16], [15, 16], [15, 16]]
您也可以只添加以下行:
sorted_list.append([0,0])
到length = len(sorted_list)
之上的代码,然后您的代码将按预期工作。
您可以使用itertools
模块:
import itertools
sorted_list = [[8, 13], [8, 14], [8, 15], ...]
def getvalues(pairs):
column_list = []
# Group the pairs by their first element
for key, pairs in itertools.groupby(sorted_list, lambda e: e[0]):
# Compose a list from the pairs' second elements
column_list.append([e[1] for e in pairs])
return column_list
然后您可以调用getvalues(sorted_list)
,它将返回您想要的输出:
[[13, 14, 15, 16, 17], [11, 12, 13, 14, 15, 16, 17, 18], ...]