📜  Python|将元组列表转换为数字

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

Python|将元组列表转换为数字

给定一个元组列表,任务是将其转换为存在于列表元素中的所有数字的列表。

让我们讨论执行此任务的某些方式。

方法 #1:使用re

将元组列表转换为列表元素中存在的所有数字的列表的最简洁易读的方法是使用re

# Python code to convert list of tuples into
# list of all digits which exists
# in elements of list.
  
# Importing
import re
  
# Input list initialization
lst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
  
# Using re
temp = re.sub(r'[\[\]\(\), ]', '', str(lst))
  
# Using set
Output = [int(i) for i in set(temp)]
  
# Printing output
print("Initial List is :", lst)
print("Output list is :", Output)
输出:


方法 #2:使用itertools.chain()lambda()

这是使用lambda()执行此特定任务的另一种方法。

# Python code to convert list of tuples into
# list of all digits which exists
# in elements of list.
  
# Importing
from itertools import chain
  
# Input list initialization
lst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
  
# using lambda
temp = map(lambda x: str(x), chain.from_iterable(lst))
  
# Output list initialization
Output = set()
  
# Adding element in Output
for x in temp:
    for elem in x:
        Output.add(elem)
  
# Printing output
print("Initial List is :", lst)
print("Output list is :", Output)
输出: