Python - 提取 Monodigit 元素
给定数字列表,提取所有只有相似数字的数字。
Input : test_list = [463, 888, 123, ‘aaa’, 112, 111, ‘gfg’, 939, 4, ‘ccc’]
Output : [888, ‘aaa’, 111, 4, ‘ccc’]
Explanation : All elements having single unique digit or character.
Input : test_list = [463, “GFG”, 8838, 43, 991]
Output : []
Explanation : No element found to be having only single digit.
方法 #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))
输出:
The original list is : [463, 888, 123, ‘aaa’, 112, 111, ‘gfg’, 939, 4, ‘ccc’]
Extracted Numbers : [888, ‘aaa’, 111, 4, ‘ccc’]
方法 #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))
输出:
The original list is : [463, 888, 123, ‘aaa’, 112, 111, ‘gfg’, 939, 4, ‘ccc’]
Extracted Numbers : [888, ‘aaa’, 111, 4, ‘ccc’]