比较数组的指数

问题描述 投票:0回答:1

我有三个数组,我的目标是比较每个情况下的指数和选择最大的数量。例如,我有三个数组,我的目标是比较指数,并在每种情况下选择最大数量。

    a = [1,5,3,2,1]
    b = [34,1,5,4,7]
    c = [5,2,4,12,2]

我也有四个变量来存放计数。

    a_count = 0
    b_count = 0
    c_count = 0
    no_count = 0

如果在a中找到了索引0的最大数字,那么a_count += 1,b和c也一样,分别是b_count和c_count。但是,如果在任何情况下,某一个索引的数字都是相似的,那么no_count += 1。

我有使用zip收集列表中每个索引的最大值的经验,但这有一些不同,我甚至不知道如何开始使用它。

python
1个回答
0
投票
    a = [2,4,2,1,4]
    b = [1,2,4,2,5]
    c = [5,1,1,3,9]

    a_count = 0
    b_count = 0
    c_count = 0
    no_count = 0

    def function(list1,list2, list3): #def returns 3rd list 
        max_list = [max(value) for value in zip(list1, list2, list3)]
        return max_list

    bob = function(a,b,c)

    for i in range(len(bob)):
        if bob[i] == a[i]:
            a_count += 1
        elif bob[i] == b[i]:
            b_count += 1
        elif bob[i] == c[i]:
            c_count += 1
        else:
            no_count += 1

能够有它的工作,使用这种天真的方式。


0
投票

有更好的方法,但这是可行的,而且相当易读。

a = [1,5,3,2,1]
b = [34,1,5,4,7]
c = [5,2,4,12,2]
a_count = 0
b_count = 0
c_count = 0
no_count = 0

for A,B,C in zip(a,b,c): # Take one element from each list at a time.
    D = max(A,B,C)
    if   A == B == D: no_count += 1
    elif A == C == D: no_count += 1
    elif B == C == D: no_count += 1
    elif A == D: a_count += 1
    elif B == D: b_count += 1
    elif C == D: c_count += 1

0
投票

如果我很好地理解了你的问题,这可能就是你要找的东西。

a = [1, 5, 3, 2, 1]
b = [34, 1, 5, 4, 7]
c = [5, 2, 4, 12, 2]

# Create placeholder list

vals = [0, 0, 0, 0]

# Loop through the triplets of elements a[i], b[i], c[i]

for elem in zip(a, b, c):
    if len(elem) != len(set(elem)):
        vals[3] += 1
    else:
        vals[elem.index(max(elem))] += 1

a_count, b_count, c_count, no_count = vals
print(a_count, b_count, c_count, no_count)
# 1 3 1 0

关于实现的一些评论. 首先,为了方便起见,我们创建了一个占位符列表。vars 其元素对应于 a_count, b_count, c_count, no_count 分别。然后,我们循环浏览三胞胎的值。a[i], b[i], c[i] (这是用for循环中的zip函数完成的)。在这个循环中,首先我们测试三联体的长度是否等于三联体元素的集合的长度(因为集合只能有唯一的元素,这就保证了没有重复),如果这个条件不成立,那么我们就增加相应的值为 a_count, b_count, c_count.

© www.soinside.com 2019 - 2024. All rights reserved.