【问题标题】:How to sum up the coordinates (tuples) between 2 lists in Python?如何总结 Python 中 2 个列表之间的坐标(元组)?
【发布时间】:2018-01-23 16:18:11
【问题描述】:

输入:列表 A 和 B,长度相同,每个列表是一对 (x,y) 数字。

输出:一个对(x,y)的列表,其中i th对的第一个元素是第一个元素的总和A中的第i个对和B中的第i个对的第一个元素。

例子:

A=[(1, 2), (10, 20)]

B=[(3, 4), (30, 40)]

返回:

[(4, 6), (40, 60)]

【问题讨论】:

  • 那么你尝试了什么?

标签: python list tuples coordinates list-comprehension


【解决方案1】:

你可以使用zip:

A=[(1,2),(10,20)]
B=[(3,4),(30,40)]
new_a = [(c+d, e+h) for (c, e), (d, h) in zip(A, B)]

输出:

[(4, 6), (40, 60)]

【讨论】:

    【解决方案2】:

    另外一个没有zip的班轮:

    A=[(1,2),(10,20)]
    B=[(3,4),(30,40)]
    result=map(lambda x, y: map(lambda i, j: i+j, x, y), A, B)
    

    查看结果:

    print([tuple(i) for i in result])
    # --> [(4, 6), (40, 60)]
    

    【讨论】:

      猜你喜欢
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多