Python range() 没有给我一个列表 [英] Python range( ) is not giving me a list

查看:55
本文介绍了Python range() 没有给我一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 范围方面遇到初学者问题.

Having a beginner issue with Python range.

我正在尝试生成一个列表,但是当我输入时:

I am trying to generate a list, but when I enter:

def RangeTest(n):

    #

    list = range(n)
    return list

print(RangeTest(4))

打印的是range(0,4)而不是[0,1,2,3]

我错过了什么?

提前致谢!

推荐答案

您使用的是 Python 3,其中 range() 返回不可变序列类型"而不是列表对象(Python 2).

You're using Python 3, where range() returns an "immutable sequence type" instead of a list object (Python 2).

你会想做:

def RangeTest(n):
    return list(range(n))

如果你习惯了 Python 2,那么 range() 等价于 Python 2 中的 xrange().

If you're used to Python 2, then range() is equivalent to xrange() in Python 2.

顺便说一下,不要覆盖 list 内置类型.这甚至会阻止您使用 list(),正如我在我的回答中所展示的那样.

By the way, don't override the list built-in type. This will prevent you from even using list() as I have shown in my answer.

这篇关于Python range() 没有给我一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆