python - 遍历具有范围的python列表中的项目列表
问题描述
我有一个类似这样的列表,里面有一个范围:
我想把它作为一个逗号分隔的值来扩展范围。
当我尝试使用 forloop 遍历列表中的项目时,我没有得到想要的结果。
a = ['1','2','3-10','15-20']
b = []
for item in a:
if '-' in item:
print('The value of item is :' , item)
start = item.split('-')[0]
print('The value of start is :' , start)
end = item.split('-')[1]
print('The value of end is :' , end)
for i in range(int(start),int(end)):
b.append(i)
else:
b.append(item)
print('The value of b is : ', b)
range 不包括最后一个元素。有更好的方法来处理这个吗?
解决方案
在末尾添加 +1,因为范围不包括最后一个数字
a = ['1','2','3-10','15-20']
b = []
for item in a:
if '-' in item:
print('The value of item is :' , item)
start = item.split('-')[0]
print('The value of start is :' , start)
end = item.split('-')[1]
print('The value of end is :' , end)
for i in range(int(start),int(end)+1):
b.append(i)
else:
b.append(item)
print('The value of b is : ', b)
如果它解决了您的问题,请接受并打勾;)
推荐阅读
- c# - Linq通过select将匿名转换为实体对象
- python - 将 PostreSQL 枚举类型转换为 Django 客户字段
- database - DBMS_CRYPTO.ENCRYPT 在不同的 oracle DB 版本中返回不同的结果
- assembly - 为 IAR 装配调试 ARM Cortex-M 硬故障
- node.js - 使用 websocket 使用 Node.js 进行 Amazon Transcribe 流式传输
- excel - 从上个月的文件中获取一些数据到当月的报告中
- css - 如何使用 Material UI 应用我的 CRA 应用程序的 scss 样式?
- php - 如何将我的工作 Laravel 5.5 升级到 Laravel 6.0
- vba - CLICK 事件中的 VBA MSHFLEXGRID 错误 .ROW 信息
- r - 为什么列选择的 data.table 表示法会影响速度