我有三个数组,我的目标是比较索引并在每种情况下选择最大数。例如:
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收集列表中每个索引的最大值的经验,但这有所不同,我什至不知道如何开始使用它。
答案 0 :(得分: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
答案 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
能够以这种幼稚的方式使其工作
答案 2 :(得分: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
的相应值。