在Python中如何使用append在循环中存储值

2024-04-20 10:57:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了一个函数(results),它包含一个for循环,其结果是一个随机数(a)。例如,如果循环运行10次,它将生成10个不同的数字。我想把这些数字存储在循环中的一个列表中,然后打印出来看看生成了什么数字。在

我想用append,但我不知道怎么做。这是到目前为止我的代码,尽管print语句不起作用(我得到一个错误消息,说我没有正确地使用append)。在

import maths

def results():
    items = []
    for _ in range(1,10):
        a = maths.numbers()
        items.append(a)
    print(items)

Tags: 函数代码import消息列表for定义错误
3条回答

你可以这样做:

import maths

list_with_numbers=[]

def results():
    for _ in range(1,10):
        a = maths.numbers()
        list_with_numbers.append(a)
    print(list_with_numbers)

这是显而易见的,但不要忘记所有的功能本身。在

append是一个必须在列表中使用的方法,因此基本上您应该这样做:randomList.append(a)并且不要忘记在函数开始时预先初始化列表:randomList = []

.append需要在列表上调用,而不是在a上调用。list还需要在循环之外初始化,以便能够append对其进行初始化。以下是您的方法的固定版本:

from random import random

def results():
    # First, initialize the list so that we have a place to store the random values
    items = []
    for _ in range(1,10):
        # Generate the next value
        a = random()

        # Add the new item to the end of the list
        items.append(a)

    # Return the list
    return items

append()方法上的Here is some more documentation,它进一步解释了它的工作原理。在

还值得注意的是,range生成从start值到stop参数(但不包括)的值。因此,如果您的意图是生成10个值,那么您应该执行range(0, 10),因为range(1, 10)只会给您9个值。在

如果您想更进一步,可以使用list comprehension来避免同时使用^{cd4>},并提供一个参数来指示需要多少个随机数:

^{pr2}$

相关问题 更多 >