2012-07-09 41 views
7

我需要根据元组(start,end)设置列表的子集为特定值。Python - 将列表范围设置为一个特定值

目前我在做这个:

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

这似乎并没有对我好。是否有更多pythonic方法?

+1

您可以使用片分配的解决方案更高效的版本由@MartijnPieters,但我觉得你的方法是好的。顺便说一下,索引的复数是_indices_。 – wim 2012-07-09 12:39:00

+2

说实话,他们这样做的方式很好,可读性强,我不认为把它压缩到一行就能增加任何东西。 – 2012-07-09 12:39:01

+2

@wim,我也喜欢_indices_,但大多数现代词典都认为这两个词都是可以接受的。 – senderle 2012-07-09 12:43:20

回答

11

采用分片分配:

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) 

您可能希望存储上限非包容性,以更好的发挥蟒蛇,并避免所有的+ 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] 
+5

+1“将上限存储为非包含”。 n + 1个bug是巨大的痛苦。 – senderle 2012-07-09 12:41:54

2
>>> L = list("qwerty") 
>>> L 
['q', 'w', 'e', 'r', 't', 'y'] 
>>> L[2:4] = ["foo"] * (4-2) 
>>> L 
['q', 'w', 'foo', 'foo', 't', 'y'] 
1

下面是使用itertools.repeat

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