📌  相关文章
📜  Python – 从列表中的范围中提取元素

📅  最后修改于: 2022-05-13 01:55:40.290000             🧑  作者: Mango

Python – 从列表中的范围中提取元素

给定一个列表和一个具有范围的元组列表,从列表中提取这些范围内的所有元素。

方法#1:使用循环+列表切片

在此,我们使用列表切片提取每个范围,并对每个范围使用循环迭代,并继续将提取的切片扩展到扩展列表。

Python3
# Python3 code to demonstrate working of 
# Extract elements from Ranges in List
# Using loop + list slicing 
  
# initializing list
test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing ranges
range_list = [(2, 4), (7, 8), (10, 12)]
  
res = []
for ele in range_list:
      
    # extending ranges
    res.extend(test_list[ele[0] : ele[1] + 1])
  
# printing result 
print("Ranges elements : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Extract elements from Ranges in List
# Using list comprehension
from itertools import chain
  
# initializing list
test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing ranges
range_list = [(2, 4), (7, 8), (10, 12)]
  
# using one-liner to solve this problem
res = list(chain.from_iterable([test_list[ele[0] : ele[1] + 1] for ele in range_list]))
  
# printing result 
print("Ranges elements : " + str(res))


输出
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
Ranges elements : [4, 6, 7, 5, 4, 4, 6, 9]

方法#2:使用列表推导

在此,我们应用与上述函数类似的方法,不同之处在于列表推导用于以紧凑的形式解决此问题。

Python3

# Python3 code to demonstrate working of 
# Extract elements from Ranges in List
# Using list comprehension
from itertools import chain
  
# initializing list
test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing ranges
range_list = [(2, 4), (7, 8), (10, 12)]
  
# using one-liner to solve this problem
res = list(chain.from_iterable([test_list[ele[0] : ele[1] + 1] for ele in range_list]))
  
# printing result 
print("Ranges elements : " + str(res))
输出
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
Ranges elements : [4, 6, 7, 5, 4, 4, 6, 9]