📌  相关文章
📜  用于获取给定元素的下一个未显示元素的Python程序

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

用于获取给定元素的下一个未显示元素的Python程序

给定一个数字列表和列表中的一个特定元素,任务是编写一个Python程序来获取下一个未显示的元素到给定元素的第一次出现,即在给定元素之前不会出现的元素。

例子:

方法 #1:使用set() + sorted() + index()

在这种情况下,使用 set() 和 sorted() 将列表转换为保留顺序的唯一元素列表。然后 index() 用于获取 number 的索引,结果列表中它的下一个元素是所需的元素。

Python3
# Python3 code to demonstrate working of
# Next different element in list
# Using set() + sorted() + index()
 
# initializing list
test_list = [3, 4, 6, 6, 3, 2, 3, 5, 6, 3, 4, 5, 5, 3, 6]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing element
nex_to_ele = 6
 
# sorting removing duplicated keeping order
temp = sorted(set(test_list), key=lambda sub: test_list.index(sub))
 
# getting next index
num_idx = temp.index(nex_to_ele)
 
# checking for last index for overflow
if num_idx == len(temp) - 1:
    res = None
 
# getting next index as result
else:
    res = temp[num_idx + 1]
 
# printing result
print("Next different element : " + str(res))


Python3
# Python3 code to demonstrate working of
# Next different element in list
# Using next() + iter() + sorted() + set()
 
# initializing list
test_list = [3, 4, 6, 6, 3, 2, 3, 5, 6, 3, 4, 5, 5, 3, 6]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing element
nex_to_ele = 6
 
# sorting removing duplicated keeping order
temp = sorted(set(test_list), key=lambda sub: test_list.index(sub))
 
temp_itr = iter(temp)
flag = 0
for idx in range(0, len(temp)):
 
    # if last element is element to find
    if idx == len(temp) - 1:
        flag = 1
 
    # breaking when element is found
    if next(temp_itr) == nex_to_ele:
        break
 
if flag:
    res = None
else:
 
    # next element is answer
    res = next(temp_itr)
 
# printing result
print("Next different element : " + str(res))


输出:

方法 #2:使用next() + iter() + sorted() + set()

在这种情况下,我们不使用 index() 来获取元素索引,而是使用用户迭代器方法递增到下一个迭代器,直到找到元素。它的下一个元素是结果。

蟒蛇3

# Python3 code to demonstrate working of
# Next different element in list
# Using next() + iter() + sorted() + set()
 
# initializing list
test_list = [3, 4, 6, 6, 3, 2, 3, 5, 6, 3, 4, 5, 5, 3, 6]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing element
nex_to_ele = 6
 
# sorting removing duplicated keeping order
temp = sorted(set(test_list), key=lambda sub: test_list.index(sub))
 
temp_itr = iter(temp)
flag = 0
for idx in range(0, len(temp)):
 
    # if last element is element to find
    if idx == len(temp) - 1:
        flag = 1
 
    # breaking when element is found
    if next(temp_itr) == nex_to_ele:
        break
 
if flag:
    res = None
else:
 
    # next element is answer
    res = next(temp_itr)
 
# printing result
print("Next different element : " + str(res))

输出: