📜  Python – 列出具有给定数字的元素

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

Python – 列出具有给定数字的元素

给定元素列表和数字 K,提取所有包含 K 位的数字。

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

这是可以执行此任务的方式之一。在此,我们将数字和元素转换为字符串,然后检查它是否在该元素内。元素迭代在列表理解内完成,以获得单行解决方案。

Python3
# Python3 code to demonstrate working of
# Elements with K digit
# Using list comprehension + str()
 
# initializing list
test_list = [56, 72, 875, 9, 173]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 7
 
# extracting all elements with digit K using
# in operator after string conversion using str()
res = [ele for ele in test_list if str(K) in str(ele)]
 
# printing result
print("Elements with digit K : " + str(res))


Python3
# Python3 code to demonstrate working of
# Elements with K digit
# Using filter() + lambda + str()
 
# initializing list
test_list = [56, 72, 875, 9, 173]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 7
 
# using filter() and lambda to perform conditionals
# using str() to perform data type conversions
res = list(filter(lambda ele: str(K) in str(ele), test_list))
 
# printing result
print("Elements with digit K : " + str(res))


输出
The original list is : [56, 72, 875, 9, 173]
Elements with digit K : [72, 875, 173]

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

这是解决此问题的另一种方法。在此,我们使用 filter() + lambda 和 str() 来检查条件并提取所需的元素。

Python3

# Python3 code to demonstrate working of
# Elements with K digit
# Using filter() + lambda + str()
 
# initializing list
test_list = [56, 72, 875, 9, 173]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 7
 
# using filter() and lambda to perform conditionals
# using str() to perform data type conversions
res = list(filter(lambda ele: str(K) in str(ele), test_list))
 
# printing result
print("Elements with digit K : " + str(res))
输出
The original list is : [56, 72, 875, 9, 173]
Elements with digit K : [72, 875, 173]