📜  Python程序仅从具有某些特定数字的列表中提取数字

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

Python程序仅从具有某些特定数字的列表中提取数字

给定元素列表,提取具有特定数字的数字。

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

在这里,我们根据目标列表中的元素检查数字中的每个元素是否存在,如果在列表中找到所有元素,则返回元素。

Python3
# Python3 code to demonstrate working of 
# Elements with specific digits
# Using list comprehension + all()
  
# initializing list
test_list = [345, 23, 128, 235, 982]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing digit list 
dig_list = [2, 3, 5, 4]
  
# checking for all digits using all()
res = [sub for sub in test_list if all(int(ele) in dig_list for ele in str(sub))]
  
# printing result 
print("Extracted elements : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Elements with specific digits
# Using filter() + lambda + all()
  
# initializing list
test_list = [345, 23, 128, 235, 982]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing digit list 
dig_list = [2, 3, 5, 4]
  
# filter() used to filter from logic 
res = list(filter(lambda sub : all(int(ele) in dig_list for ele in str(sub)), test_list))
  
# printing result 
print("Extracted elements : " + str(res))


输出:

The original list is : [345, 23, 128, 235, 982]
Extracted elements : [345, 23, 235]

方法 #2:使用filter() + lambda + all()

在这种情况下,元素过滤是使用 filter() + lambda 完成的,all() 用于检查其他列表中的所有数字。

蟒蛇3

# Python3 code to demonstrate working of 
# Elements with specific digits
# Using filter() + lambda + all()
  
# initializing list
test_list = [345, 23, 128, 235, 982]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing digit list 
dig_list = [2, 3, 5, 4]
  
# filter() used to filter from logic 
res = list(filter(lambda sub : all(int(ele) in dig_list for ele in str(sub)), test_list))
  
# printing result 
print("Extracted elements : " + str(res))

输出:

The original list is : [345, 23, 128, 235, 982]
Extracted elements : [345, 23, 235]