【问题标题】:Multiple Tuple to Two-Pair Tuple in Python?Python中的多个元组到两对元组?
【发布时间】:2009-04-16 15:02:38
【问题描述】:

最好的分割方法是什么:

tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')

进入这个:

tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]

假设输入总是有偶数个值。

【问题讨论】:

  • 你可能不想要一个名为 tuple 的变量,因为它会覆盖内置函数 tuple()。

标签: python data-structures tuples


【解决方案1】:

zip()是你的朋友:

t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip(t[::2], t[1::2])

【讨论】:

  • +1 因为它很漂亮而且我不知道 [::] 语法
  • 不适用于元组 = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i ') # 注意最后一个'i',这使得元组长度为奇数
  • @dfa:你说它不起作用是什么意思?是否指定了在奇数长度输入的情况下应如何形成新列表?
  • ops,我刚刚读到:“假设输入总是有偶数个值。”
  • @dfa: 好吧,如果输入有奇数个元素,剩下的元素应该怎么办?它应该是一个元素元组还是应该是(x,None)?您必须根据预期的输出按摩您的输入。
【解决方案2】:
[(tuple[a], tuple[a+1]) for a in range(0,len(tuple),2)]

【讨论】:

    【解决方案3】:

    或者,使用itertools(对于grouper,请参阅recipe):

    from itertools import izip
    def group2(iterable):
       args = [iter(iterable)] * 2
       return izip(*args)
    
    tuples = [ab for ab in group2(tuple)]
    

    【讨论】:

      【解决方案4】:

      我根据Peter Hoffmann's answer 提供此代码作为对dfa's comment 的响应。

      无论您的元组是否有偶数个元素,都可以保证工作。

      [(tup[i], tup[i+1]) for i in range(0, (len(tup)/2)*2, 2)]
      

      (len(tup)/2)*2 range 参数计算小于或等于元组长度的最大偶数,因此无论元组是否具有偶数个元素,都可以保证工作。

      该方法的结果将是一个列表。可以使用tuple() 函数将其转换为元组。

      示例:

      def inPairs(tup):
          return [(tup[i], tup[i+1]) for i in range(0, (len(tup)/2)*2, 2)]
      
      # odd number of elements
      print("Odd Set")
      odd = range(5)
      print(odd)
      po = inPairs(odd)
      print(po)
      
      # even number of elements
      print("Even Set")
      even = range(4)
      print(even)
      pe = inPairs(even)
      print(pe)
      

      输出

      奇数集 [0, 1, 2, 3, 4] [(0, 1), (2, 3)] 偶数集 [0, 1, 2, 3] [(0, 1), (2, 3)]

      【讨论】:

        【解决方案5】:

        以下是任意大小块的通用配方,如果它可能不总是 2:

        def chunk(seq, n):
            return [seq[i:i+n] for i in range(0, len(seq), n)]
        
        chunks= chunk(tuples, 2)
        

        或者,如果您喜欢迭代器:

        def iterchunk(iterable, n):
            it= iter(iterable)
            while True:
                chunk= []
                try:
                    for i in range(n):
                        chunk.append(it.next())
                except StopIteration:
                    break
                finally:
                    if len(chunk)!=0:
                        yield tuple(chunk)
        

        【讨论】:

        • 我认为你的意思是 range(0, len(seq), n),而不是 range(0, len(seq))
        猜你喜欢
        • 2022-10-08
        • 2022-11-27
        • 2012-03-23
        • 1970-01-01
        • 1970-01-01
        • 2015-09-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多