📜  Python – K 个中间元素

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

Python – K 个中间元素

给定一个列表,提取出现在列表中间的 K 个元素。

方法#1:使用循环

在此,我们首先制定范围,提取一半 pre middle 和 half post middle 元素,然后使用循环来提取所需的元素。在奇数长度列表中均匀工作。

Python3
# Python3 code to demonstrate working of 
# K middle elements
# Using loop
  
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# computing strt, and end index 
strt_idx = (len(test_list) // 2) - (K // 2)
end_idx = (len(test_list) // 2) + (K // 2)
  
# using loop to get indices 
res = []
for idx in range(len(test_list)):
      
    # checking for elements in range
    if idx >= strt_idx and idx <= end_idx:
        res.append(test_list[idx])
  
# printing result 
print("Extracted elements list : " + str(res))


Python3
# Python3 code to demonstrate working of 
# K middle elements
# Using list slicing 
  
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# computing strt, and end index 
strt_idx = (len(test_list) // 2) - (K // 2)
end_idx = (len(test_list) // 2) + (K // 2)
  
# slicing extracting middle elements
res = test_list[strt_idx: end_idx + 1]
  
# printing result 
print("Extracted elements list : " + str(res))


输出
The original list is : [2, 3, 5, 7, 8, 5, 3, 5, 9]
Extracted elements list : [5, 7, 8, 5, 3]

方法#2:使用列表切片 

在此,在范围计算步骤之后,使用列表切片进行范围提取。

蟒蛇3

# Python3 code to demonstrate working of 
# K middle elements
# Using list slicing 
  
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# computing strt, and end index 
strt_idx = (len(test_list) // 2) - (K // 2)
end_idx = (len(test_list) // 2) + (K // 2)
  
# slicing extracting middle elements
res = test_list[strt_idx: end_idx + 1]
  
# printing result 
print("Extracted elements list : " + str(res))
输出
The original list is : [2, 3, 5, 7, 8, 5, 3, 5, 9]
Extracted elements list : [5, 7, 8, 5, 3]