📜  Python|在列表中加入循环

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

Python|在列表中加入循环

有时,在处理竞争性编程中的图问题时,我们有一个配对列表,我们需要找出其中是否存在可能的循环,并打印该循环中的所有元素。让我们讨论一下可以解决这个问题的特定方法。

方法:使用yield +循环+生成器
执行的粗暴方法是使用生成器并在我们知道元素肯定形成循环时继续打印值,这是通过无限循环完成的,并在找不到更多匹配项时停止。

# Python3 code to demonstrate working of
# Join cycle in list
# Using yield + loop + generator
  
# helper function to perform this task 
def cycle(test_list, val, stop = None):
    temp = dict(test_list)
    stop = stop if stop is not None else val
    while True:
        yield (val)
        val = temp.get(val, stop)
        if val == stop: break
  
# initializing list
test_list = [[6, 7], [9, 6], [7, 9]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Join cycle in list
# Using yield + loop + generator
# printing result
print("The cycle elements are : ")
for ele in cycle(test_list, 6):
    print(ele)
输出 :
The original list is : [[6, 7], [9, 6], [7, 9]]
The cycle elements are : 
6
7
9