请用python写一段代码,从csv读取一连串数据,如果数据是连续的,就用闭区间表示,如果数据是单独的(非连续的),就单独打印出来
时间: 2023-10-09 10:14:59 浏览: 49
假设我们有一个名为data.csv的CSV文件,其中包含一列整数数据。可以使用Python内置的csv模块来读取这个文件,并根据数据的连续性进行处理。以下是示例代码:
```python
import csv
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
data = [int(row[0]) for row in reader]
ranges = []
start = end = data[0]
for i in range(1, len(data)):
if data[i] == end + 1:
end = data[i]
else:
if start == end:
ranges.append(str(start))
else:
ranges.append(f'{start}-{end}')
start = end = data[i]
if start == end:
ranges.append(str(start))
else:
ranges.append(f'{start}-{end}')
print(', '.join(ranges))
```
这个脚本首先使用csv模块从data.csv文件中读取整数数据,并将其存储在名为data的列表中。然后,它遍历这个列表,构建连续的范围并将它们存储在名为ranges的列表中。最后,它将这些范围打印出来。
阅读全文
相关推荐



















