16

我需要根据带有 bounds 的元组将列表的子集设置为特定值(start,end)

目前我正在这样做:

indexes = range(bounds[0], bounds[1] + 1)
for i in indexes:
   my_list[i] = 'foo'

这对我来说似乎不太好。有没有更蟒蛇的方法?

4

3 回答 3

20

使用切片分配:

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]
于 2012-07-09T12:34:14.583 回答
5
>>> L = list("qwerty")
>>> L
['q', 'w', 'e', 'r', 't', 'y']
>>> L[2:4] = ["foo"] * (4-2)
>>> L
['q', 'w', 'foo', 'foo', 't', 'y']
于 2012-07-09T12:35:41.060 回答
1

这是@MartijnPieters 使用的解决方案的更有效版本itertools.repeat

import itertools
lower, upper = bounds
upper += 1
my_list[lower:upper] = itertools.repeat('foo', (upper - lower))
于 2012-07-09T13:03:34.773 回答