【问题标题】:Convert list of tuples into list of all the integers used in that list将元组列表转换为该列表中使用的所有整数的列表
【发布时间】:2019-03-07 03:04:07
【问题描述】:

这里是 Python 初学者。我有一个像这样的元组列表:

[(100, 1), (50, 2), (25, 4), (20, 5), (10, 10)]

我想把它转换成

[0, 2, 4, 5, 1]

必须有一种比不断替换每个字符更快的方法:

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)]

然而,我什至找不到一次替换多个不相邻字符的方法。我错过了什么明显的东西吗?

【问题讨论】:

    标签: python regex string list tuples


    【解决方案1】:

    如果你想使用你的替换方法,确实有一个简单的方法来做到这一点:

    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)]
    

    外部[] 中指定的任何字符都将被替换。

    【讨论】:

      【解决方案2】:

      如果顺序不一定重要,您可以使用集合:

      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'}
      

      如果顺序很重要,请使用列表:

      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']
      

      【讨论】:

      • 只是一个建议,您可以将map的功能设置为str,如map(str, ...)
      猜你喜欢
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 2018-12-19
      • 2012-06-05
      • 1970-01-01
      • 2022-09-27
      • 2016-09-28
      相关资源
      最近更新 更多