📜  Python|自定义列表拆分

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

Python|自定义列表拆分

开发和有时机器学习应用程序需要以自定义方式将列表拆分为较小的列表,即在必须执行拆分的某些值上。这是一个非常有用的实用程序,值得了解。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + zip()

通过结合列表理解和zip()的强大功能,可以完成此任务。在此,我们压缩列表的开头和结尾,然后在列表到达时继续对其进行切片并从中删除新列表。

# Python3 code to demonstrate 
# to perform custom list split
# using list comprehension + zip()
  
# initializing string  
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
  
# initializing split index list 
split_list = [2, 5, 7]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# printing original split index list
print ("The original split index list : " + str(split_list))
  
# using list comprehension + zip()
# to perform custom list split
res = [test_list[i : j] for i, j in zip([0] + 
          split_list, split_list + [None])]
  
# printing result
print ("The splitted lists are : " +  str(res))
输出:
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists are : [[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]


方法 #2:使用itertools.chain() + zip()

列表理解函数执行的获取拆分块的任务也可以使用链函数完成。当我们希望处理更大的列表时,这更有用,因为这种方法更有效。

# Python3 code to demonstrate 
# to perform custom list split
# using itertools.chain() + zip()
from itertools import chain
  
# initializing string  
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
  
# initializing split index list 
split_list = [2, 5, 7]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# printing original split index list
print ("The original split index list : " + str(split_list))
  
# using itertools.chain() + zip()
# to perform custom list split
temp = zip(chain([0], split_list), chain(split_list, [None]))
res = list(test_list[i : j] for i, j in temp)
  
# printing result
print ("The splitted lists are : " +  str(res))
输出:
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists are : [[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]