Python – 从元组列表中提取数字
有时,在使用Python列表时,我们可能会遇到需要从元组列表中提取所有数字的问题。这种问题可以在数据领域和日常编程中找到它的应用。让我们讨论可以执行此任务的某些方式。
Input : test_list = [(15, 3), (3, 9)]
Output : [9, 5, 3, 1]
Input : test_list = [(15, 3)]
Output : [5, 3, 1]
方法 #1:使用 map() + chain.from_iterable() + set() + loop
上述功能的组合可以用来解决这个问题。在此,我们使用 chain.from_iterable() 执行扁平化列表的任务,然后使用 brute 方法提取数字。 set() 用于删除重复的数字。
Python3
# Python3 code to demonstrate working of
# Extract digits from Tuple list
# Using map() + chain.from_iterable() + set() + loop
from itertools import chain
# initializing list
test_list = [(15, 3), (3, 9), (1, 10), (99, 2)]
# printing original list
print("The original list is : " + str(test_list))
# Extract digits from Tuple list
# Using map() + chain.from_iterable() + set() + loop
temp = map(lambda ele: str(ele), chain.from_iterable(test_list))
res = set()
for sub in temp:
for ele in sub:
res.add(ele)
# printing result
print("The extracted digits : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract digits from Tuple list
# Using regex expression
import re
# initializing list
test_list = [(15, 3), (3, 9), (1, 10), (99, 2)]
# printing original list
print("The original list is : " + str(test_list))
# Extract digits from Tuple list
# Using regex expression
temp = re.sub(r'[\[\]\(\), ]', '', str(test_list))
res = [int(ele) for ele in set(temp)]
# printing result
print("The extracted digits : " + str(res))
输出
The original list is : [(15, 3), (3, 9), (1, 10), (99, 2)]
The extracted digits : {'1', '0', '3', '2', '9', '5'}
方法#2:使用正则表达式
这是可以执行此任务的另一种方式。在此,使用适当的正则表达式来提取所需的唯一数字。
Python3
# Python3 code to demonstrate working of
# Extract digits from Tuple list
# Using regex expression
import re
# initializing list
test_list = [(15, 3), (3, 9), (1, 10), (99, 2)]
# printing original list
print("The original list is : " + str(test_list))
# Extract digits from Tuple list
# Using regex expression
temp = re.sub(r'[\[\]\(\), ]', '', str(test_list))
res = [int(ele) for ele in set(temp)]
# printing result
print("The extracted digits : " + str(res))
输出
The original list is : [(15, 3), (3, 9), (1, 10), (99, 2)]
The extracted digits : [5, 9, 2, 0, 1, 3]