Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果有任何方法可以将此代码添加到函数中?_Python - Fatal编程技术网

Python 如果有任何方法可以将此代码添加到函数中?

Python 如果有任何方法可以将此代码添加到函数中?,python,Python,可以将带有注释的代码添加到函数中吗?如果是的话,我会怎么做 import random random_list = [] list_length = 20 while len(random_list) < list_length: random_list.append(random.randint(0,10)) # Add to function below: index = 0 count = 0 while index < len(random_list):

可以将带有注释的代码添加到函数中吗?如果是的话,我会怎么做

import random

random_list = []
list_length = 20

while len(random_list) < list_length:
    random_list.append(random.randint(0,10))

# Add to function below:
index = 0
count = 0

while index < len(random_list):
    if random_list[index] == 9:
        count = count + 1
        index = index + 1
# End of add to function

print random_list
print count

您不需要所有这些代码来计算列表中9的数量:

count = random_list.count(9)
但如果您确实想使用该代码,则可以使用以下函数:

def count_function(sequence, item):
    index = 0
    count = 0

    while index < len(sequence):
        if sequence[index] == item:
            count = count + 1
        index = index + 1

    return count

阅读巨蟒。谢谢。这太棒了。我还在学习,我只是想知道如何做到这一点
import random


def count_function(sequence, item):
    index = 0
    count = 0

    while index < len(sequence):
        if sequence[index] == item:
            count = count + 1
        index = index + 1

    return count


random_list = []
list_length = 20

while len(random_list) < list_length:
    random_list.append(random.randint(0,10))

count = count_function(random_list, 9)

print random_list
print count
def count_function(iterable, item):
    count = 0

    for item_from_iterable in iterable:
        if item_from_iterable == item:
            count += 1

    return count