Python-将列表范围设置为特定值 [英] Python - set list range to a specific value
本文介绍了Python-将列表范围设置为特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要基于边界为(start,end)
的元组将列表的子集设置为特定值.
I need to set a subset of a list to a specific value based on a tuple with bounds (start,end)
.
目前我正在这样做:
indexes = range(bounds[0], bounds[1] + 1)
for i in indexes:
my_list[i] = 'foo'
这对我来说似乎不好.还有更Python化的方法吗?
This doesn't seem good to me. Is there a more pythonic approach?
推荐答案
使用切片分配:
my_list[bounds[0]:bounds[1] + 1] = ['foo'] * ((bounds[1] + 1) - bounds[0])
或使用局部变量只添加一次+ 1
:
or using local variables to add your + 1
only once:
lower, upper = bounds
upper += 1
my_list[lower:upper] = ['foo'] * (upper - lower)
您可能希望将上限存储为非包含性,以便更好地使用python并避免所有+ 1
计数.
You may want to store the upper bound as non-inclusive, to play better with python and avoid all the + 1
counts.
演示:
>>> 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]
这篇关于Python-将列表范围设置为特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文