📌  相关文章
📜  测试所有 y 是否出现在列表中 x 之后的Python程序

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

测试所有 y 是否出现在列表中 x 之后的Python程序

给定一个列表,测试是否所有出现的 y 都在列表中出现的 x 之后。

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

在此,我们检查列表中 x 的索引,然后运行循环获取 y 的出现,如果在 x 索引之前出现任何 y,则结果为 False。

Python3
# Python3 code to demonstrate working of 
# Test if y occurs after x in List
# Using loop + index()
  
# initializing list
test_list = [4, 5, 6, 2, 4, 5, 2, 9]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing x, y 
x, y = 6, 2
  
# getting index of x 
xidx = test_list.index(x)
  
res = True 
for idx, ele in enumerate(test_list):
      
    # checking for y and comparing index 
    if ele == y and idx < xidx:
        res = False 
        break
  
# printing result 
print("Do all y occur after x : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Test if y occurs after x in List
# Using all() + index()
  
# initializing list
test_list = [4, 5, 6, 2, 4, 5, 2, 9]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing x, y 
x, y = 6, 2
  
# getting index of x 
xidx = test_list.index(x)
  
# checking for all indices of y in list 
res = all(idx > xidx for idx, ele in enumerate(test_list) if ele == y)
  
# printing result 
print("Do all y occur after x : " + str(res))



输出:

The original list is : [4, 5, 6, 2, 4, 5, 2, 9]
Do all y occur after x : True

方法 #2:使用all() + index()

在此,我们使用 all() 测试 y 的所有索引,而 index() 用于获取列表中 x 的索引。

蟒蛇3

# Python3 code to demonstrate working of 
# Test if y occurs after x in List
# Using all() + index()
  
# initializing list
test_list = [4, 5, 6, 2, 4, 5, 2, 9]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing x, y 
x, y = 6, 2
  
# getting index of x 
xidx = test_list.index(x)
  
# checking for all indices of y in list 
res = all(idx > xidx for idx, ele in enumerate(test_list) if ele == y)
  
# printing result 
print("Do all y occur after x : " + str(res))


输出:

The original list is : [4, 5, 6, 2, 4, 5, 2, 9]
Do all y occur after x : True