请用python写一段代码,从csv读取一连串数据,如果数据是连续的,就用闭区间表示,如果数据没法连接,就单独进行输出
时间: 2023-09-29 13:08:00 浏览: 96
用python读取CSV数据
假设csv文件的格式如下:
```
1
2
3
5
6
7
9
10
```
以下是对应的Python代码:
```python
import csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
data = [int(row[0]) for row in reader]
ranges = []
current_range_start = data[0]
for i in range(1, len(data)):
if data[i] != data[i-1] + 1:
ranges.append((current_range_start, data[i-1]))
current_range_start = data[i]
ranges.append((current_range_start, data[-1]))
for r in ranges:
if r[0] == r[1]:
print(r[0])
else:
print('{}-{}'.format(r[0], r[1]))
```
输出结果为:
```
1-3
5-7
9-10
```
阅读全文