我有一个表示年范围的整数对的列表,需要计算连续(一年内)对的联合范围。
示例输入:
ts_list = [[1777, 1777], [1778, 1783], [1786, 1791], [1792, 1795]]
所需的输出
[[1777, 1781], [1786, 1795]]
我尝试了while和while循环,并且可以在第一个脱节之前获得并集,但是我对如何正确进行迭代感到困惑-例如产生
的新列表 [[1777, 1783], [1778, 1783], [1786, 1795]]
然后返回类型错误:'int' object is not subscriptable"
。第一对和第三对是正确的,但第二对是无关的
ts_list = [[1777, 1777], [1778, 1781], [1786, 1791], [1792, 1795]]
newlist=[]
last = ts_list[len(ts_list)-1][1]
for x in range(len(ts_list)):
ts=ts_list[x]
start = ts[0]
end = ts[1]
ts_next = ts_list[x+1] if x<len(ts_list)-1 else last
if ts_next[0]-end > 1:
# next is disjoint, break out
newlist.append([start,end])
else:
# next is contiguous (within 1 year)
newlist.append([start,ts_next[1]])
答案 0 :(得分:2)
您可以这样做:
ts_list = [[1777, 1777], [1778, 1781], [1786, 1791], [1792, 1795]]
# We start with the first range
out = [ts_list[0]]
for start, end in ts_list[1:]:
if start <= out[-1][1] + 1:
# if the new range starts at most one year
# after the end of the previous one, we extend it:
out[-1][1] = end
else:
# otherwise, we append this new range to the output
out.append([start, end])
print(out)
# [[1777, 1781], [1786, 1795]]
答案 1 :(得分:1)
使用集合/列表理解:
ts_list = [[1777, 1777], [1778, 1781], [1786, 1791], [1792, 1795]]
# Get all years that are contained in one of the date ranges, including start and end year.
# Using a set ensures that each year appears only once.
all_years = {y for years in ts_list for y in range(years[0], years[1] + 1)}
# Get start years (years where the previous year is not in all_years)
# and end years (years where the following year is not in all_years).
start_years = [y for y in all_years if y - 1 not in all_years]
end_years = [y for y in all_years if y + 1 not in all_years]
# Combine start and end years. To match the right ones, sort first.
start_years.sort()
end_years.sort()
result = [[start_year, end_year] for start_year, end_year in zip(start_years, end_years)]
print(result)
# [[1777, 1781], [1786, 1795]]