简体   繁体   English

比较两个列表的列表元素(略有不同)

[英]Comparing list elements of two lists (with a twist)

I have two lists of integers (only positive ones): a and b. 我有两个整数列表(只有正数):a和b。 Now, I want to compare a[0] with b[0], a[1] with b[1], a[2] with b[2] and so on, but I don't know how to. 现在,我想将a [0]与b [0],a [1]与b [1],a [2]与b [2]进行比较,依此类推,但是我不知道如何做。

More specifically, I want to know the distance between a[0] and b[0] and so on, and save the results in a list (or, which would be even better, I want a list of percentages of, if the bigger integer would be 100%, how much percent the smaller one would be of the bigger one (fe 2 is 50% of 4)). 更具体地说,我想知道a [0]和b [0]之间的距离,等等,然后将结果保存在列表中(或者,如果更大,我希望列出百分比的列表,如果更大的话)整数将是100%,较小的整数将占较大的整数的百分比(fe 2是4的50%)。

I have Python 3.7.3. 我有Python 3.7.3。

You can use a list comprehension with zip , and take the abs of the difference between the elements in each tuple : 您可以将列表理解与zip ,并获取每个tuple元素之间的差异的abs

[abs(i-j) for i,j in zip(l1,l2)]

And if you want the percentual difference, as you mention, you can use string formatting: 如前所述,如果您希望百分比差异,则可以使用字符串格式:

['{0:.2f}%'.format((min(i,j)/max(i,j))*100) for i,j in zip(l1,l2)]

Where in both cases, by zipping both lists you are creating a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables: 在两种情况下,通过压缩两个列表都可以创建一个元组列表,其中第i个元组包含每个参数序列或可迭代对象中的第i个元素:

list(zip(l1,l2))
# [(8, 3), (5, 6), (2, 4), (1, 3)]

For instance: 例如:

l1 = [8,5,2,1]
l2 = [3,6,4,3]

['{0:.2f}%'.format((min(i,j)/max(i,j))*100) for i,j in zip(l1,l2)]
# ['37.50%', '83.33%', '50.00%', '33.33%']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM