[英]Convert list of tuples into list of all the integers used in that list
Python beginner here. Python初学者在这里。 I have a list of tuples like so:
我有一个像这样的元组列表:
[(100, 1), (50, 2), (25, 4), (20, 5), (10, 10)]
[(100,1),(50,2),(25,4),(20,5),(10,10)]
and I want to convert it into 我想将其转换为
[0, 2, 4, 5, 1]
[0,2,4,5,1]
There has to be a faster way to do this than constantly replacing each character: 与不断替换每个字符相比,必须有一种更快的方法:
strfp1 = re.sub('\(','',str(factor_pairs)); strfp2 = re.sub('\)','',strfp1); strfp3 = re.sub('\[','',strfp2); strfp4 = re.sub(']','',strfp3); strfp5 = re.sub(',','',strfp4); strfp6 = re.sub(' ','',strfp5)
factor_numbers = [int(i) for i in set(strfp6)]
Yet, I couldn't even find a way to replace multiple non-adjacent characters at once. 但是,我什至找不到找到一次替换多个不相邻字符的方法。 Am I missing something obvious?
我是否缺少明显的东西?
If you wanted to use your method of replacement, there is indeed an easy way to do this: 如果您想使用替换方法,确实有一种简单的方法:
import re
factor_pairs = [(100, 1), (50, 2), (25, 4), (20, 5), (10, 10)]
s = re.sub(r'[\[\]\(\), ]', '', str(factor_pairs))
factor_numbers = [int(i) for i in set(s)]
Any character specified in the outer []
's will be replaced. 在外部
[]
指定的任何字符都将被替换。
You can use a set if order necessarily not matters: 如果顺序不一定重要,则可以使用一组:
from itertools import chain
lst = [(100, 1), (50, 2), (25, 4), (20, 5), (10, 10)]
flst = map(lambda x: str(x), chain.from_iterable(lst))
s = set()
for x in flst:
for i in x:
s.add(i)
print(s)
# {'2', '1', '0', '5', '4'}
If order matters, use a list: 如果订单很重要,请使用以下列表:
from itertools import chain
lst = [(100, 1), (50, 2), (25, 4), (20, 5), (10, 10)]
flst = map(lambda x: str(x), chain.from_iterable(lst))
s = []
for x in flst:
for i in x:
if i not in s:
s.append(i)
print(s)
# ['1', '0', '5', '2', '4']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.