📜  Python - 提取 Monodigit 元素

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

Python - 提取 Monodigit 元素

给定数字列表,提取所有只有相似数字的数字。

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

在这里,我们使用列表推导式迭代所有元素, all()用于检查所有数字与第一个数字的相等性。

Python3
# Python3 code to demonstrate working of
# Extract Monodigit elements
# Using list comprehension + all()
  
# initializing list
test_list = [463, 888, 123, "aaa", 112, 111, "gfg", 939, 4, "ccc"]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# all() checks for all similar digits
res = [sub for sub in test_list if all(
    str(ele) == str(sub)[0] for ele in str(sub))]
  
# printing result
print("Extracted Numbers : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract Monodigit elements
# Using filter() + lambda + all()
  
# initializing list
test_list = [463, 888, 123, "aaa", 112, 111, "gfg", 939, 4, "ccc"]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# all() checks for all similar digits
# filter() used for filtering
res = list(filter(lambda sub: all(str(ele) == str(
    sub)[0] for ele in str(sub)), test_list))
  
# printing result
print("Extracted Numbers : " + str(res))


输出:

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

在这里,我们使用lambda函数执行过滤任务, filter()all()再次用于检查所有数字的相等性。

蟒蛇3

# Python3 code to demonstrate working of
# Extract Monodigit elements
# Using filter() + lambda + all()
  
# initializing list
test_list = [463, 888, 123, "aaa", 112, 111, "gfg", 939, 4, "ccc"]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# all() checks for all similar digits
# filter() used for filtering
res = list(filter(lambda sub: all(str(ele) == str(
    sub)[0] for ele in str(sub)), test_list))
  
# printing result
print("Extracted Numbers : " + str(res))

输出: