gpt4 book ai didi

Python找到区间的连续兴趣

转载 作者:行者123 更新时间:2023-11-28 22:53:57 25 4
gpt4 key购买 nike

我厌倦了多种方法,但未能完成这一项工作。他们都只使用 2 个列表或列表范围。最有希望的是:

infile = open('file','r')

for line in infile:
line = line.split()
f = range(int(line[0]),int(line[1]))

results_union = set().union(*f)
print results_union

我有一个包含开始和结束位置的文件:(已排序)

1 5
1 3
1 2
2 4
3 6
9 11
9 16
12 17

我希望输出为:

1 6
9 17

最佳答案

尝试以下操作:

def group(data):
data = sorted(data)
it = iter(data)
a, b = next(it)
for c, d in it:
if b >= c: # Use `if b > c` if you want (1,2), (2,3) not to be
# treated as intersection.
b = max(b, d)
else:
yield a, b
a, b = c, d
yield a, b


with open('file') as f:
data = [map(int, line.split()) for line in f]

for a, b in group(data):
print a, b

例子:

>>> data = (9,16), (1,5), (1,3), (1,2), (3,6), (9,11), (12,17), (2,4),
>>> list(group(data))
[(1, 6), (9, 17)]

关于Python找到区间的连续兴趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18745693/

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