使用分片分配:
my_list[bounds[0]:bounds[1] + 1] = ['foo'] * ((bounds[1] + 1) - bounds[0])
或使用局部变量
+ 1仅添加一次:
lower, upper = boundsupper += 1my_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]



