📜  删除列表中 x 之前出现的每个 y 的Python程序

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

删除列表中 x 之前出现的每个 y 的Python程序

给定一个列表,删除列表中元素 x 之前出现的所有 y。

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

在这里,我们使用 index() 获取 x 的索引,并检查 x 之前的 y,如果存在,则从结果列表中排除。使用列表比较来执行迭代和比较。

Python3
# Python3 code to demonstrate working of 
# Remove each y occurrence before x in List
# Using list comprehension + index()
  
# initializing list
test_list = [4, 5, 7, 4, 6, 7, 4, 9, 1, 4]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing x and y 
x, y = 6, 4
  
# getting index using index()
xidx = test_list.index(x)
  
# retain all values other than y, and y if its index greater than x index
res = [ele for idx, ele in enumerate(test_list) if ele != y or (ele == y and idx > xidx) ]
  
# printing result 
print("Filtered List " + str(res))


Python3
# Python3 code to demonstrate working of 
# Remove each y occurrence before x in List
# Using loop + index()
  
# initializing list
test_list = [4, 5, 7, 4, 6, 7, 4, 9, 1, 4]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing x and y 
x, y = 6, 4
  
# getting index using index()
xidx = test_list.index(x)
  
# filtering using comparison operators
res = []
for idx, ele in enumerate(test_list):
  if ele != y or (ele == y and idx > xidx):
    res.append(ele)
  
# printing result 
print("Filtered List " + str(res))


输出:

The original list is : [4, 5, 7, 4, 6, 7, 4, 9, 1, 4]
Filtered List [5, 7, 6, 7, 4, 9, 1, 4]

方法 #2:使用循环 + index()

过滤任务是使用循环中的运算符完成的,index() 用于获取列表中 x 的索引。

蟒蛇3

# Python3 code to demonstrate working of 
# Remove each y occurrence before x in List
# Using loop + index()
  
# initializing list
test_list = [4, 5, 7, 4, 6, 7, 4, 9, 1, 4]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing x and y 
x, y = 6, 4
  
# getting index using index()
xidx = test_list.index(x)
  
# filtering using comparison operators
res = []
for idx, ele in enumerate(test_list):
  if ele != y or (ele == y and idx > xidx):
    res.append(ele)
  
# printing result 
print("Filtered List " + str(res))

输出:

The original list is : [4, 5, 7, 4, 6, 7, 4, 9, 1, 4]
Filtered List [5, 7, 6, 7, 4, 9, 1, 4]