【问题标题】:Convert list of tuples such that [(a,b,c)] converts to [(a,b),(a,c)]转换元组列表,使得 [(a,b,c)] 转换为 [(a,b),(a,c)]
【发布时间】:2020-07-08 08:55:48
【问题描述】:

对我将如何做到这一点的想法?我希望元组中的第一个值与每个连续值配对。这样每个结果元组都是从第一个值开始的一对。

我需要这样做:[(a,b,c)] --> [(a,b),(a,c)]

【问题讨论】:

  • 请用您尝试过的代码更新您的问题。
  • 你尝试过什么,到底有什么问题?

标签: python python-3.x list tuples


【解决方案1】:

你可以试试这个。

(t,)=[('a','b','c')]

[(t[0],i) for i in t[1:]]
# [('a', 'b'), ('a', 'c')]

使用itertools.product

it=iter(('a','b','c'))
list(itertools.product(next(it),it))
# [('a', 'b'), ('a', 'c')]

使用itertools.repeat

it=iter(('a','b','c'))
list(zip(itertools.repeat(next(it)),it))
# [('a', 'b'), ('a', 'c')]

【讨论】:

    【解决方案2】:

    如果您的元组是任意长度,您可以编写一个简单的生成器:

    def make_pairs(iterable):
        iterator = iter(iterable)
        first = next(iterator)
        for item in iterator:
            yield first, item
    

    示例结果:

    my_tuple = ('a', 'b', 'c', 'd')
    list(make_pairs(my_tuple))
    Out[170]: [('a', 'b'), ('a', 'c'), ('a', 'd')]
    

    这是一种节省内存的解决方案。

    【讨论】:

      【解决方案3】:

      您可以将成对的元组附加到列表中:

      original = [(1,2,3)]
      
      def makePairs(lis):
          ret = []
          for t in lis:
              ret.append((t[0],t[1]))
              ret.append((t[0],t[2]))
          return ret
      
      
      print(makePairs(original))
      

      输出:

      [(1, 2), (1, 3)]
      

      【讨论】:

        【解决方案4】:

        使用itertools 的组合模块的解决方案。

        from itertools import combinations  
        arr = (['a','b','c'])
        for i in list(combinations(arr, 2)):
            if(i[0]==arr[0]):
                print(i ,end = " ")
        

        这将给出一个解决方案('a', 'b') ('a', 'c')

        【讨论】:

          【解决方案5】:
          a = [('a','b','c')]
          a = a[0]
          a = [tuple([a[0], a[index]]) for index in range(1, len(a))]
          

          试试这个!

          【讨论】:

            猜你喜欢
            • 2020-07-15
            • 2011-05-30
            • 1970-01-01
            • 1970-01-01
            • 2018-09-14
            • 2014-03-23
            • 1970-01-01
            • 2012-11-12
            • 2021-12-27
            相关资源
            最近更新 更多