📜  Python – 删除字符直到 K 元素

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

Python – 删除字符直到 K 元素

有时,在使用Python时,我们可能会遇到需要让列表中的所有元素出现在列表中特定字符之后的问题。这类问题可以在数据域和 Web 开发中得到应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是可以执行此任务的蛮力方法。在此,我们迭代循环直到找到 K,然后开始追加字符,看起来就像删除了 K 之前的元素。

# Python3 code to demonstrate 
# Remove characters till K element
# using loop
  
# Initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K 
K = 'best'
  
# Remove characters till K element
# using loop
res = []
flag = 0
for ele in test_list:
    if ele == K:
        flag = 1 
        continue
    if flag:
        res.append(ele)
  
# printing result 
print ("List elements after removing all before K : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
List elements after removing all before K : ['for', 'geeks']

方法 #2:使用index() + 列表理解
这是可以执行此任务的另一种方式。在这种情况下,我们首先找到元素的索引,然后使用列表推导 + enumerate() 仅追加该 K 之后的元素。

# Python3 code to demonstrate 
# Remove characters till K element
# using list comprehension + enumerate() + index()
  
# Initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K 
K = 'best'
  
# Remove characters till K element
# using list comprehension + enumerate() + index()
temp = test_list.index(K)
res = [ele for idx, ele in enumerate(test_list) if idx > temp]
  
# printing result 
print ("List elements after removing all before K : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
List elements after removing all before K : ['for', 'geeks']