在 Python 中从列表中提取范围
Extract a range from a List in Python
使用列表切片从列表中提取范围,例如
new_list = a_list[3:6]
. 列表切片的语法是list[start:stop:step]
索引start
是包含的,stop
索引是排他的(直到但不包括)。
a_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] # ✅ get a slice of a list (index 3 up to index 6) new_list = a_list[3:6] print(new_list) # 👉️ [8, 10, 12] # --------------------------------------- # ✅ extract specific (start, stop) ranges from a list ranges = [(0, 2), (3, 5)] new_list = [] for start, stop in ranges: new_list.extend([*a_list[start:stop]]) print(new_list) # 👉️ [2, 4, 8, 10] # --------------------------------------- # ✅ extract indices of list items that meet a condition indices = [index for index, item in enumerate(a_list) if item > 14] print(indices) # 👉️ [7, 8, 9]
第一个示例使用列表切片从列表中提取范围。
a_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] new_list = a_list[3:6] print(new_list) # 👉️ [8, 10, 12]
列表切片的语法是my_list[start:stop:step]
.
start
索引是包含的,索引stop
是排他的(最多,但不包括)。a_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] print(a_list[1:3]) # 👉️ [4, 6] print(a_list[2:5]) # 👉️ [6, 8, 10]
Python 索引是从零开始的,因此列表中的第一项的索引为0
,最后一项的索引为-1
或len(my_list) - 1
。
如果需要从列表中提取某些索引范围内的元素,请使用
for
循环。
a_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] ranges = [(0, 2), (3, 5)] new_list = [] for start, stop in ranges: new_list.extend([*a_list[start:stop]]) print(new_list) # 👉️ [2, 4, 8, 10]
我们使用for
循环来遍历ranges
.
start
索引,第二个是stop
索引(直到但不包括该索引)。list.extend
方法采用可迭代对象并通过附加可迭代对象中的所有项目来扩展列表。
my_list = ['bobby'] my_list.extend(['hadz', '.', 'com']) print(my_list) # 👉️ ['bobby', 'hadz', '.', 'com']
我们还使用可迭代解包*
运算符在调用list.extend()
方法时解包切片。
*可迭代解包运算符
使我们能够在函数调用、推导式和生成器表达式中解包可迭代对象。
If you want to make the stop
indices in the ranges inclusive, add 1
to each
stop
index.
a_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] ranges = [(1, 2), (4, 5)] new_list = [] for start, stop in ranges: new_list.extend([*a_list[start:stop + 1]]) print(new_list) # 👉️ [4, 6, 10, 12]
We added 1
to the stop
index when slicing, so the stop
index is inclusive.
a_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] indices = [index for index, item in enumerate(a_list) if item > 14] print(indices) # 👉️ [7, 8, 9]
List comprehensions are used to perform some operation for every element or
select a subset of elements that meet a condition.
We used the enumerate()
function to get access to the index of the current
iteration.
The enumerate
function takes an iterable and returns an enumerate object containing tuples
where the first element is the index and the second is the corresponding item.
my_list = ['bobby', 'hadz', 'com'] for index, item in enumerate(my_list): print(index, item) # 👉️ 0 bobby, 1 hadz, 2 com
在每次迭代中,我们检查当前列表项是否满足特定条件并返回相应的索引。
如果您需要在列表中查找满足条件的项目,您可以使用相同的方法。
a_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] indices = [item for item in a_list if item > 14] print(indices) # 👉️ [16, 18, 20]
我们不遍历enumerate
对象,而是直接遍历列表并返回大于 的元素14
。
新列表仅包含满足条件的项目。