📜  Python程序从集合中的列表中提取元素

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

Python程序从集合中的列表中提取元素

给定一个列表,任务是编写一个Python程序来提取所有在集合中出现匹配的元素。

方法#1:使用循环

在这种情况下,每个列表元素都被迭代并使用 in运算符检查其在集合中的存在,如果找到则附加到结果。

Python3
# Python3 code to demonstrate working of
# Elements from list in set
# Using loop
  
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
               
# printing original list
print("The original list is : " + str(test_list))
  
# initializing search set
search_set = {6, 2, 8}
  
res = []
for ele in test_list:
      
    # check if element is present in set
    if ele in search_set:
        res.append(ele)
  
# printing result
print("Set present list elements : " + str(res))


Python3
# Python3 code to demonstrate working of
# Elements from list in set
# Using repeat() + from_iterable() + count()
from itertools import chain, repeat
  
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
               
# printing original list
print("The original list is : " + str(test_list))
  
# initializing search set
search_set = {6, 2, 8}
  
# repeat repeats all the occurrences of elements
res = list(chain.from_iterable((repeat(ele, test_list.count(ele)) 
                                for ele in search_set)))
  
# printing result
print("Set present list elements : " + str(res))


输出:

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]

方法#2:使用repeat() + from_iterable() + count()

在此,我们测试列表中的每个集合元素,并通过使用 count() 计算所需的计数重复使用 repeat()。此结果中不保持顺序。

蟒蛇3

# Python3 code to demonstrate working of
# Elements from list in set
# Using repeat() + from_iterable() + count()
from itertools import chain, repeat
  
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
               
# printing original list
print("The original list is : " + str(test_list))
  
# initializing search set
search_set = {6, 2, 8}
  
# repeat repeats all the occurrences of elements
res = list(chain.from_iterable((repeat(ele, test_list.count(ele)) 
                                for ele in search_set)))
  
# printing result
print("Set present list elements : " + str(res))

输出:

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]