【问题标题】:Python Tuple UnpackingPython 元组解包
【发布时间】:2015-05-15 04:51:15
【问题描述】:

如果我有

 nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')]

并且愿意

nums = [1, 2, 3]
words= ['one', 'two', 'three']

我将如何以 Python 的方式做到这一点?我花了一分钟才意识到为什么以下不起作用

nums, words = [(el[0], el[1]) for el in nums_and_words]

我很好奇是否有人可以提供类似的方式来实现我正在寻找的结果。

【问题讨论】:

    标签: python list-comprehension iterable-unpacking


    【解决方案1】:

    使用列表理解..

    nums = [nums_and_words[x][0] for x in xrange(len(nums_and_words)) ]
    words = [nums_and_words[x][1] for x in xrange(len(nums_and_words)) ]
    
    测试这是否有效
    print nums ,'&', words 
    

    【讨论】:

      【解决方案2】:

      使用zip,然后解压:

      nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')]
      nums, words = zip(*nums_and_words)
      

      实际上,这会“解包”两次:首先,将列表列表传递给 zip*,然后将结果分配给两个变量。

      您可以将zip(*list_of_lists) 视为“转置”参数:

         zip(*[(1, 'one'), (2, 'two'), (3, 'three')])
      == zip(  (1, 'one'), (2, 'two'), (3, 'three') )
      == [(1, 2, 3), ('one', 'two', 'three')]
      

      注意,这会给你元组;如果你真的需要列表,你必须map 结果:

      nums, words = map(list, zip(*nums_and_words))
      

      【讨论】:

        【解决方案3】:

        只需解压缩并创建列表:

        nums = list(zip(*nums_and_words)[0])
        word = list(zip(*nums_and_words)[1])
        

        请参阅zip 文档。

        【讨论】:

        • 我希望避免将它分成两行。我希望摆脱的初始设置是... num = filter(lambda x: x[0], num_and_words) 和 words = filter(lambda x: x[1], num_and_words)
        猜你喜欢
        • 1970-01-01
        • 2012-08-19
        • 2021-10-06
        • 1970-01-01
        • 2018-02-13
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        • 2018-04-26
        相关资源
        最近更新 更多