我需要根据带有 bounds 的元组将列表的子集设置为特定值(start,end)
。
目前我正在这样做:
indexes = range(bounds[0], bounds[1] + 1)
for i in indexes:
my_list[i] = 'foo'
这对我来说似乎不太好。有没有更蟒蛇的方法?
我需要根据带有 bounds 的元组将列表的子集设置为特定值(start,end)
。
目前我正在这样做:
indexes = range(bounds[0], bounds[1] + 1)
for i in indexes:
my_list[i] = 'foo'
这对我来说似乎不太好。有没有更蟒蛇的方法?
使用切片分配:
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]
>>> L = list("qwerty")
>>> L
['q', 'w', 'e', 'r', 't', 'y']
>>> L[2:4] = ["foo"] * (4-2)
>>> L
['q', 'w', 'foo', 'foo', 't', 'y']
这是@MartijnPieters 使用的解决方案的更有效版本itertools.repeat
import itertools
lower, upper = bounds
upper += 1
my_list[lower:upper] = itertools.repeat('foo', (upper - lower))