Python - 使用 for 循环构建/创建列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18752171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:41:51  来源:igfitidea点击:

Python - Building/creating a list using for loop

pythonlistfor-loop

提问by StacyM

I'm taking this online Python courseand trying to solve the following problem called Coding Exercise: It's Natural:

我正在学习这个在线 Python 课程,并试图解决以下称为编码练习的问题:很自然:

Write a function naturalNumbers which takes a positive integer n as input, and returns a list [1, 2, ...] consisting of the first n natural numbers.

编写一个函数 naturalNumbers,它接受一个正整数 n 作为输入,并返回一个由前 n 个自然数组成的列表 [1, 2, ...]。

Do I even need a for loop to create a list? Here's my code (which doesn't work obviously). Keep in mind, they have not taught list comprehension. I found this concept on stackoverflow.

我什至需要一个 for 循环来创建一个列表吗?这是我的代码(显然不起作用)。请记住,他们没有教过列表理解。我在 stackoverflow 上发现了这个概念。

def naturalNumbers(n):
   list = [n+1 for i in n]
   return list

Should I take another approach where I create multiple lists of 1,2,3...n and concatenate them all together like [1] + [2] + [3]....

我是否应该采取另一种方法,创建多个 1,2,3...n 列表并将它们连接在一起,如 [1] + [2] + [3]....

采纳答案by arshajii

Do I even need a for loop to create a list?

我什至需要一个 for 循环来创建一个列表吗?

No, you can (and in general circumstances should) use the built-in function range():

不,您可以(并且在一般情况下应该)使用内置函数range()

>>> range(1,5)
[1, 2, 3, 4]

i.e.

IE

def naturalNumbers(n):
    return range(1, n + 1)

Python 3's range()is slightly different in that it returns a rangeobject and not a list, so if you're using 3.x wrap it all in list(): list(range(1, n + 1)).

Python 3 的range()稍微不同之处在于它返回一个range对象而不是一个列表,因此如果您使用 3.x,请将其全部包装在list(): 中list(range(1, n + 1))

回答by abarnert

There are two problems with your attempt.

你的尝试有两个问题。

First, you've used n+1instead of i+1, so you're going to return something like [5, 5, 5, 5]instead of [1, 2, 3, 4].

首先,您使用了n+1代替i+1,因此您将返回类似[5, 5, 5, 5]代替的内容[1, 2, 3, 4]

Second, you can't for-loop over a number like n, you need to loop over some kind of sequence, like range(n).

其次,你不能循环遍历for一个数字,比如n,你需要循环某种序列,比如range(n)

So:

所以:

def naturalNumbers(n):
    return [i+1 for i in range(n)]

But if you already have the rangefunction, you don't need this at all; you can just return range(1, n+1), as arshaji showed.

但是如果你已经有了这个range功能,你就根本不需要这个;你可以return range(1, n+1),正如阿尔沙吉所展示的那样。

So, how would you build this yourself? You don't have a sequence to loop over, so instead of for, you have to build it yourself with while:

那么,你将如何自己构建这个?您没有要循环的序列,因此for您必须使用while以下命令自己构建它:

def naturalNumbers(n):
    results = []
    i = 1
    while i <= n:
        results.append(i)
        i += 1
    return results

Of course in real-life code, you should always use forwith a range, instead of doing things manually. In fact, even for this exercise, it might be better to write your own rangefunction first, just to use it for naturalNumbers. (It's already pretty close.)

当然,在现实生活中的代码中,您应该始终使用forwith range,而不是手动操作。事实上,即使对于这个练习,最好先编写自己的range函数,只是为了将其用于naturalNumbers. (已经很接近了。)



There is one more option, if you want to get clever.

如果你想变得聪明,还有一种选择。

If you have a list, you can slice it. For example, the first 5 elements of my_listare my_list[:5]. So, if you had an infinitely-long list starting with 1, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using countor by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice. So:

如果你有一个列表,你可以切片它。例如, 的前 5 个元素my_listmy_list[:5]。因此,如果您有一个以 开头的无限长列表1,那将很容易。不幸的是,你不能有一个无限长的列表……但是你可以有一个很容易模拟的迭代器,通过使用count或编写你自己的 2-liner 等价物。而且,虽然您不能对迭代器进行切片,但您可以使用islice. 所以:

from itertools import count, islice
def naturalNumbers(n):
    return list(islice(count(1), n)))

回答by Harry Han

Here are a few ways to create a list with N of continuous natural numbers starting from 1.

这里有几种方法可以创建一个包含 N 个从 1 开始的连续自然数的列表。

1 range:

1个范围:

def numbers(n): 
    return range(1, n+1);

2 List Comprehensions:

2 列表理解:

def numbers(n):
    return [i for i in range(1, n+1)]

You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!

您可能想研究 xrange 方法和生成器的概念,这些在 Python 中很有趣。祝你学习顺利!