如何阻止我的循环在i的末尾结束



提示为:

使用PyCharm,在lab8下,在目录练习下,创建一个名为编写一个函数nbrs_greater,接受2个整数列表作为参数,并且返回整数列表,该整数列表指示第二列表中有多少整数大于第一列表中的每个整数。例如:nbrs_greater([3, 4, 1, 2, 7], [10, 1, 4, 2, 5, 3])返回[3, 2, 5, 4, 1]

我的代码有时可以工作,但当我输入时:

nbrs_greater([20, 5, 1, 6], [1, 4, 8, 12, 16])

它不会继续超过6,并返回[0, 3, 4]而不是[0, 3, 4, 3],因为有三个值的6大于列表2中的6。

这是我的原始代码--------

def nbrs_greater(list_1, list_2):
final_list = []
list_count = []
list_greater = []
number_of_greater = 0
for i in list_1:
for j in list_2:
if i < j:
list_greater.append(i)
number_of_greater += 1
if i > max(list_2):
list_count.append(0)
for k in list_greater:
count_list_var = list_greater.count(k)
list_count.append(count_list_var)
for h in list_count:
if h not in final_list:
final_list.append(h)
if len(final_list) == 0:
final_list.append(0)
return final_list

print(nbrs_greater([20, 5, 1, 6], [1, 4, 8, 12, 16]))

你让这件事变得比需要的要复杂得多。你不需要列出每个更大的数字来获得计数。您可以使用sum()函数来获取计数。

def nbrs_greater(list_1, list_2):
final_list = []
for i in list_1:
greater_count = sum(j > i for j in list_2)
final_list.append(greater_count)
return final_list

这里的if h not in final_list:是指final_list的数字不相同,所以它不会是两个"3"。不同的计数可以正常。

最新更新