📜  Python| K字符组列表

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

Python| K字符组列表

有时,我们可能会遇到一个问题,我们需要在作为分隔符发送的 K字符上将列表拆分为列表列表。此类问题可用于发送消息,也可用于希望拥有本机列表列表的情况。让我们讨论一些可以做到这一点的方法。

方法 #1:使用index()和列表切片
列表切片可用于从本地列表中获取子列表,索引函数可用于检查可能充当分隔符的 K字符。这样做的缺点是它仅适用于单个拆分,即只能将一个列表划分为 2 个子列表。

# Python3 code to demonstrate
# Group List on K character
# using index() + list slicing 
  
# initializing list 
test_list = ['Geeks', 'for', 'M', 'Geeks', 1, 2]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = 'M'
  
# using index() + list slicing
# Group List on K character
temp_idx = test_list.index(K)
res = [test_list[: temp_idx], test_list[temp_idx + 1: ]]
  
# print result
print("The list of sublist after separation : " + str(res))
输出 :
The original list : ['Geeks', 'for', 'M', 'Geeks', 1, 2]
The list of sublist after separation : [['Geeks', 'for'], ['Geeks', 1, 2]]

方法#2:使用循环
上面提出的方法的问题可以使用通用循环和蛮力来解决,这里我们只是寻找K字符并在之后创建一个新列表。

# Python3 code to demonstrate
# Group List on K character
# using loop
  
# initializing list 
test_list =  ['Geeks', 'M', 'for', 'M', 4, 5, 'M', 'Geeks', 'CS', 'M', 'Portal']
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = 'M'
  
# using loop
# Group List on K character
temp = []
res = []
for ele in test_list:
    if ele == K:
        res.append(temp)
        temp = []
    else:
        temp.append(ele)
res.append(temp)
  
# print result
print("The list of sublist after separation : " + str(res))
输出 :
The original list : ['Geeks', 'for', 'M', 'Geeks', 1, 2]
The list of sublist after separation : [['Geeks', 'for'], ['Geeks', 1, 2]]