【问题标题】:I want to combine a list of tuples in python [duplicate]我想在python中组合一个元组列表[重复]
【发布时间】:2020-09-19 06:35:38
【问题描述】:

我有一个 x 和 y 坐标的元组列表,例如: [(1,2), (3,4), (5,6)] 我想操纵列表成为一个 2xN 矩阵(取决于有多少数字),这样我就有一个只有 x 坐标和 y 坐标的列表。基本上我想输出: [(1,3,5), (2,4,6)] 通过一个函数,但不完全确定如何这样做。

【问题讨论】:

    标签: python list matrix tuples concatenation


    【解决方案1】:
    list(zip(*[(1, 2), (3, 4), (5, 6)]))
    

    将输出:

    [(1, 3, 5), (2, 4, 6)]
    

    >>> a = [(1, 2), (3, 4), (5, 6)]
    
    >>> zip(*a) # Returns a zipped object. 
    <zip object at 0x10c9f5540>
    
    >>> print(*a) # "Star a" unpacks the list.
    (1, 2) (3, 4) (5, 6)
    
    >>> print(a[0], a[1], a[2]) # Above is equivalent to:
    (1, 2) (3, 4) (5, 6)
    
    >>> b, c = [1, 2], [3, 4]
    
    >>> list(zip(b, c))
    [(1, 3), (2, 4)] # Zips the inputs of both lists in the pattern (b1, c1) and (b2, c2). list() converts the "zip" generator to a list. 
    
    >>> list(zip(*a)) 
    [(1, 3, 5), (2, 4, 6)] # Zips the wanted ints with the logic above.
    

    【讨论】:

    • 如果我有一个列表列表,这也可以吗?例如 [[(1, 2), (3, 4), (5, 6)], [(3,8), (4,5)]] 而我想要的是 [(1,3,5,3 ,4), (2,4,6,8,5)]?
    • 是的!它应该,因为 zip 会将(a, b), (c, d), (e, f)“转换”为(a, c, e), (b, d, f)
    猜你喜欢
    • 2015-10-30
    • 1970-01-01
    • 2015-10-02
    • 2023-02-20
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    相关资源
    最近更新 更多