2012-07-09 39 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)) 
相關問題