gpt4 book ai didi

python - 如何迭代整数对列表,计算新的 'union pairs'

转载 作者:行者123 更新时间:2023-11-30 21:56:45 25 4
gpt4 key购买 nike

我有一个表示年份范围的整数对列表,需要计算连续(1 年内)对的联合范围。

输入示例:

ts_list = [[1777, 1777], [1778, 1783], [1786, 1791], [1792, 1795]]

所需输出

[[1777, 1781], [1786, 1795]]

我已经尝试过 for 和 while 循环,并且可以在第一次不相交之前获得并集,但我对如何正确迭代感到困惑 - 例如这会产生一个新列表

[[1777, 1783], [1778, 1783], [1786, 1795]]

然后返回类型错误:'int'对象不可下标”。第一对和第三对是正确的,但第二对是无关的

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]])

最佳答案

你可以这样做:

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]]

关于python - 如何迭代整数对列表,计算新的 'union pairs',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55434497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com