繁体   English   中英

如何在Python的循环中使用附加存储值

[英]How to use append to store values within a loop in 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)

.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()方法的更多文档 ,进一步解释了它的工作方式。

还值得注意的是, range生成从起始值到(但不包括)stop参数的值。 因此,如果您打算生成10个值,则应该执行range(0, 10)因为range(1, 10)仅会给您9个值。

如果您想更进一步,可以使用列表理解来避免完全使用append ,并提供一个参数来指示您想要多少个随机数:

def results(num=10):
   return [random() for _ in range(0, num)]

# produces a list of 10 random numbers (by default)
foo = results()

# produces a list of 20 random numbers
bar = results(20)

您可以执行以下操作:

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 = []

你有一些小错误

  • 没有maths模块
  • a是数字,而不是列表。 您应该在清单上追加
  • 您在循环结束调用print ,而不是在每次迭代时都调用

    从随机导入随机

    def results():数字= []

     for _ in range(1,10): a = random() print(a) numbers.append(a) return numbers 

暂无
暂无

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

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