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

Python-将列表范围设置为特定值,python,list,python-2.7,Python,List,Python 2.7,我需要将列表的子集设置为基于具有边界的元组的特定值(开始,结束) 目前我正在这样做: indexes = range(bounds[0], bounds[1] + 1) for i in indexes: my_list[i] = 'foo' 我觉得这不太好。是否有更具python风格的方法?使用切片分配: my_list[bounds[0]:bounds[1] + 1] = ['foo'] * ((bounds[1] + 1) - bounds[0]) 或者使用局部变量只添加一次+1

我需要将列表的子集设置为基于具有边界的元组的特定值
(开始,结束)

目前我正在这样做:

indexes = range(bounds[0], bounds[1] + 1)
for i in indexes:
   my_list[i] = 'foo'
我觉得这不太好。是否有更具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
计数

演示:


这里是@MartijnPieters使用
itertools的更有效的解决方案版本。重复

import itertools
lower, upper = bounds
upper += 1
my_list[lower:upper] = itertools.repeat('foo', (upper - lower))

您可以使用切片赋值,但我认为您的方法很好。顺便说一句,索引的复数形式是索引。老实说,你这样做很好,可读性也很好,我不认为压缩成一行会增加什么。@wim,我也喜欢索引,但大多数现代字典都认为这两种形式都是可以接受的。@wim我认为“索引”在美国/加拿大可能更常见,而在英国或OzJust,“索引”更常见的是重新强调一个点,我会考虑在您的问题中使用的方法比使用切片赋值的答案更具Pythic。python的禅宗说,“简单比复杂好”。您只需将列表中的几个元素设置为一个值,不需要在其中分配切片,所做的只是通过让您计算更多的值(通过生成分配的数组)来引入更多的bug范围。保留你所拥有的。+1“将上限存储为非包容性的。”n+1错误是一个巨大的痛苦。
>>> L = list("qwerty")
>>> L
['q', 'w', 'e', 'r', 't', 'y']
>>> L[2:4] = ["foo"] * (4-2)
>>> L
['q', 'w', 'foo', 'foo', 't', 'y']
import itertools
lower, upper = bounds
upper += 1
my_list[lower:upper] = itertools.repeat('foo', (upper - lower))