我有一个如下所示的列表: 每个元组都有一个名称、起点、终点和方向:
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)]]
拆分列表有两种规则: 1) 如果相邻元组之间的 abs(start - stop) > 20,则创建一个新列表 [OR] 2) 如果相邻元组具有相反的方向,例如 ('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 在末尾插入了一个空列表,我无法弄清楚我做错了什么。有没有更Pythonic的方法来做同样的事情?
最佳答案
如果它是列表中的第一个元素,则将该元素添加到列表内的 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)]]
关于python - 根据元组中的值拆分元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26745656/