【问题标题】:How to compare the elements of the list and find the total difference between each numbers?如何比较列表的元素并找到每个数字之间的总差?
【发布时间】:2018-04-09 06:52:32
【问题描述】:

例如:

a=[123,456]
b=[789,345]

需要做的操作是(1-7)+(2-8)+(3-9)+(4-3)+(5-4)+(6-5),应该返回总数。

【问题讨论】:

  • 其实这个问题是今天在一次采访中问我的。我是python的新手。我不知道该怎么办。请帮忙。

标签: python python-3.x


【解决方案1】:
a=[123,456] 
b=[789,345]
total = 0
for aa,bb in zip(a,b):
    for aaa,bbb in zip(str(aa), str(bb)):
        total += int(aaa) - int(bbb)
print (total)

【讨论】:

    【解决方案2】:

    你可以使用zip:

    a=[123,456] 
    b=[789,345]
    a1 = ''.join(map(str, a))
    b1 = ''.join(map(str, b))
    final_sum = sum(c-d for c, d in zip(map(int, list(a1)), map(int, list(b1))))
    

    【讨论】:

    • 无需将a1b1 设为list。 +1。
    • 非常感谢。我现在明白了。非常感谢您的帮助。
    • @SnehasishSaha 很高兴为您提供帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 2020-02-09
    • 2019-01-17
    • 2021-08-08
    相关资源
    最近更新 更多