根据元组中的值分割元组列表
我有一个列表,里面的每一组数据看起来像这样:
major_list = [('a',20,30,-1),('b',31,40,-1),('c',41,50,-1),('d',51,60,+1),('z',90,100,-1),('e',61,70,+1),('f',71,80,+1)]
每组数据包含一个名字、开始时间、结束时间和一个方向:
我需要把这个列表拆分成这样:
[[('a',20,30,-1),('b',31,40,-1),('c',41,50,-1)],[('d',51,60,+1)],[('z',90,100,-1)],[('e',61,70,+1),('f',71,80,+1)]]
拆分这个列表有两个规则:
- 如果相邻的两组数据的开始时间和结束时间的差值大于20,就要新建一个列表。
- 如果相邻的两组数据的方向相反,比如说 ('c',41,50,-1) 和 ('d',51,60,+1),那么在 'c' 后面也要新建一个列表。
这是我目前的代码:
SplitList = []
for i,tup in enumerate(major_List):
if i != len(major_List)-1:
if i == 0:
tmp_list = []
next_tup = major_List[i+1]
if (abs(int(next_tup[1]) - int(tup[2])) > 20) or (next_tup[3] != tup[3]):
tmp_list.append(tup)
if tmp_list:
SplitList.append(tmp_list)
tmp_list = []
else:
tmp_list.append(tup)
但不知为什么,SplitList的最后面多了一个空列表,我搞不清楚我哪里出错了。有没有更符合Python风格的方法来实现同样的功能?
1 个回答
2
如果这是列表中的第一个元素,就把这个元素放到一个叫 final
的列表里,然后只需要检查 final
列表最后一个元素中的所需子元素,看看它们和当前的元素有什么不同:
major_list = [('a',20,30,-1),('b',31,40,-1),('c',41,50,-1),('d',51,60,+1),('z',90,100,-1),('e',61,70,+1),('f',71,80,+1)]
final = []
for ele in major_list:
if not final:
final.append([ele]) # final is empty so add the first element in a list
# check the last item of the last sublist added to final and compare to our current element
elif abs(final[-1][-1][1] - ele[2]) > 20 or final[-1][-1][3] != ele[3]:
# if it does not meet the requirement, add it to final in a new list
final.append([ele])
else:
# else add it to the last sublist
final[-1].append(ele)
print(final)
[[('a', 20, 30, -1), ('b', 31, 40, -1), ('c', 41, 50, -1)], [('d', 51, 60, 1)], [('z', 90, 100, -1)], [('e', 61, 70, 1), ('f', 71, 80, 1)]]