您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-将列表范围设置为特定值

Python-将列表范围设置为特定值

使用分片分配:

my_list[bounds[0]:bounds[1] + 1] = ['foo'] * ((bounds[1] + 1) - bounds[0])

或使用局部变量+ 1添加一次:

lower, upper = bounds
upper += 1
my_list[lower:upper] = ['foo'] * (upper - lower)

您可能希望将上限存储为非包含性,以便更好地使用python并避免所有+ 1计数。

演示:

>>> my_list = range(10)
>>> bounds = (2, 5)
>>> my_list[bounds[0]:bounds[1] + 1] = ['foo'] * ((bounds[1] + 1) - bounds[0])
>>> my_list
[0, 1, 'foo', 'foo', 'foo', 'foo', 6, 7, 8, 9]
python 2022/1/1 18:49:53 有343人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶