繁体   English   中英

试图了解我的 python 代码是如何工作的

[英]Trying to understand how my python code works

i = [1, 2, 3, 5, 5, 7, 9, 12, 14, 14,]

list_length = len(i)

def numbers_found(x):
    y = i.count(x)
    return y
    


latest_num = i[list_length - 1]

for z in range(latest_num + 1):
    print("Found", numbers_found(z), "of number", "\"" + str(z) + "\".")

我试图找出列表中有多少特定数字可用,如果我以某种方式减去 1 到列表中的最大数字(假设它是按升序排列的)并再次添加 1 就可以了。 请帮我解释一下。

让我们一步一步地分解它。

# a list. indexes shown below
#    0  1  2  3  4  5  6  7   8   9
i = [1, 2, 3, 5, 5, 7, 9, 12, 14, 14]

# getting the length of the list (10)
# or the number of elements
list_length = len(i)

# a function returning the amounts of
# times a passed value is found in the list i
def numbers_found(x):
    y = i.count(x)
    return y

# see above that list_length is 10
# but we need one less that to retrieve the last element
# which will be 14
latest_num = i[list_length - 1]

# range given 1 argument iterates from 0
# to the number you pass it but not including it
# since latest_num is 14, it won't include it
# So range(15) would iterate like
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
for z in range(latest_num + 1):
    print("Found", numbers_found(z), "of number", "\"" + str(z) + "\".")

range工作的原因是,看到range(length_of_my_list)并期望它返回完整列表的索引是很常见的。 为了实现这一点,您只需要迭代而不包括长度。 在你的情况下( 10 )。

您使用它的目的是别的。 您正在尝试查找list中所有数字的出现次数。 由于您没有将它用于索引,因此添加+ 1可以工作,因为您希望它包含14

利用

for z in range(len(i)):
     print("Found", numbers_found(z), "of number", "\"" + str(z) + "\".")

这里 len(i) 是 i 的大小,即 i 中的元素个数,range(n) = [0, 1, ..., n - 1] 即从 0 到 n-1 的所有数字,按 asc 排序。

暂无
暂无

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

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