你如何在Python中创建像PHP一样的列表?

时间:2023-01-13 09:16:56

This is an incredibly simple question (I'm new to Python).

这是一个非常简单的问题(我是Python的新手)。

I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.

我基本上想要一个像PHP数组一样的数据结构 - 也就是说,我想初始化它然后只是在其中添加值。

As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.

据我所知,这是不可能的Python,所以我有我可能想用作索引的最大值,但我无法弄清楚如何创建一个指定长度的空列表。

Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.

另外,列表是一个正确的数据结构,用于模拟它应该只是一个数组?我试图使用数组,但它似乎不满意存储字符串。

Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.

编辑:对不起,我没有很清楚地解释我在寻找什么。当我将项目添加到列表中时,我不想按顺序将它们放入,而是我想将它们插入列表中的指定插槽中。

I.e., I want to be able to do this:

即,我希望能够做到这一点:

list = []

for row in rows:
  c = list_of_categories.index(row["id"])
  print c
  list[c] = row["name"]

9 个解决方案

#1


Depending on how you are going to use the list, it may be that you actually want a dictionary. This will work:

根据您将如何使用列表,可能实际上您需要一本字典。这将有效:

d = {}

for row in rows:
  c = list_of_categories.index(row["id"])
  print c
  d[c] = row["name"]

... or more compactly:

......或更紧凑:

d = dict((list_of_categories.index(row['id']), row['name']) for row in rows)
print d

PHP arrays are much more like Python dicts than they are like Python lists. For example, they can have strings for keys.

PHP数组更像Python dicts,而不像Python列表。例如,它们可以包含键的字符串。

And confusingly, Python has an array module, which is described as "efficient arrays of numeric values", which is definitely not what you want.

令人困惑的是,Python有一个数组模块,被描述为“有效的数值数组”,这绝对不是你想要的。

#2


If the number of items you want is known in advance, and you want to access them using integer, 0-based, consecutive indices, you might try this:

如果您想要的项目数是事先知道的,并且您想要使用基于0的整数连续索引来访问它们,您可以尝试这样做:

n = 3
array = n * [None]
print array
array[2] = 11
array[1] = 47
array[0] = 42
print array

This prints:

[None, None, None]
[42, 47, 11]

#3


Use the list constructor, and append your items, like this:

使用列表构造函数,并附加您的项目,如下所示:

l = list ()
l.append ("foo")
l.append (3)
print (l)

gives me ['foo', 3], which should be what you want. See the documentation on list and the sequence type documentation.

给了我['foo',3],这应该是你想要的。请参阅列表文档和序列类型文档。

EDIT Updated

For inserting, use insert, like this:

要插入,请使用insert,如下所示:

l = list ()
l.append ("foo")
l.append (3)
l.insert (1, "new")
print (l)

which prints ['foo', 'new', 3]

打印['foo','new',3]

#4


http://diveintopython3.ep.io/native-datatypes.html#lists

You don't need to create empty lists with a specified length. You just add to them and query about their current length if needed.

您不需要创建具有指定长度的空列表。您只需添加它们并在需要时查询其当前长度。

What you can't do without preparing to catch an exception is to use a non existent index. Which is probably what you are used to in PHP.

如果不准备捕获异常,你不能做的就是使用不存在的索引。这可能是你在PHP中习惯的。

#5


You can use this syntax to create a list with n elements:

您可以使用此语法创建包含n个元素的列表:

lst = [0] * n

But be careful! The list will contain n copies of this object. If this object is mutable and you change one element, then all copies will be changed! In this case you should use:

不过要小心!该列表将包含此对象的n个副本。如果此对象是可变的并且您更改了一个元素,那么所有副本都将被更改!在这种情况下,您应该使用:

lst = [some_object() for i in xrange(n)]

Then you can access these elements:

然后你可以访问这些元素:

for i in xrange(n):
    lst[i] += 1

A Python list is comparable to a vector in other languages. It is a resizable array, not a linked list.

Python列表与其他语言中的矢量相当。它是一个可调整大小的数组,而不是链表。

#6


Sounds like what you need might be a dictionary rather than an array if you want to insert into specified indices.

如果要插入指定的索引,听起来你需要的可能是字典而不是数组。

dict = {'a': 1, 'b': 2, 'c': 3}
dict['a']

1

#7


I agree with ned that you probably need a dictionary for what you're trying to do. But here's a way to get a list of those lists of categories you can do this:

我同意你可能需要一本字典来表达你想要做的事情。但是这里有一种方法可以获得这些类别列表的列表:

lst = [list_of_categories.index(row["id"]) for row in rows]

#8


use a dictionary, because what you're really asking for is a structure you can access by arbitrary keys

使用字典,因为你真正要求的是一个你可以通过任意键访问的结构

list = {}

for row in rows:
  c = list_of_categories.index(row["id"])
  print c
  list[c] = row["name"]

Then you can iterate through the known contents with:

然后,您可以使用以下内容迭代已知内容:

for x in list.values():
  print x

Or check if something exists in the "list":

或者检查“列表”中是否存在某些内容:

if 3 in list: 
  print "it's there"

#9


I'm not sure if I understood what you mean or want to do, but it seems that you want a list which is dictonary-like where the index is the key. Even if I think, the usage of a dictonary would be a better choice, here's my answer: Got a problem - make an object:

我不确定我是否明白你的意思或想要做什么,但似乎你想要一个类似于dictonary的列表,其中索引是关键。即使我认为,使用dictonary将是一个更好的选择,这是我的答案:有问题 - 制作一个对象:

class MyList(UserList.UserList):

NO_ITEM = 'noitem'

def insertAt(self, item, index):

    length = len(self)
    if index < length:
        self[index] = item
    elif index == length:
        self.append(item)
    else:
        for i in range(0, index-length):
            self.append(self.NO_ITEM)
        self.append(item)

Maybe some errors in the python syntax (didn't check), but in principle it should work. Of course the else case works also for the elif, but I thought, it might be a little harder to read this way.

也许python语法中的一些错误(没有检查),但原则上它应该工作。当然,其他情况也适用于elif,但我想,这可能有点难以阅读。

#1


Depending on how you are going to use the list, it may be that you actually want a dictionary. This will work:

根据您将如何使用列表,可能实际上您需要一本字典。这将有效:

d = {}

for row in rows:
  c = list_of_categories.index(row["id"])
  print c
  d[c] = row["name"]

... or more compactly:

......或更紧凑:

d = dict((list_of_categories.index(row['id']), row['name']) for row in rows)
print d

PHP arrays are much more like Python dicts than they are like Python lists. For example, they can have strings for keys.

PHP数组更像Python dicts,而不像Python列表。例如,它们可以包含键的字符串。

And confusingly, Python has an array module, which is described as "efficient arrays of numeric values", which is definitely not what you want.

令人困惑的是,Python有一个数组模块,被描述为“有效的数值数组”,这绝对不是你想要的。

#2


If the number of items you want is known in advance, and you want to access them using integer, 0-based, consecutive indices, you might try this:

如果您想要的项目数是事先知道的,并且您想要使用基于0的整数连续索引来访问它们,您可以尝试这样做:

n = 3
array = n * [None]
print array
array[2] = 11
array[1] = 47
array[0] = 42
print array

This prints:

[None, None, None]
[42, 47, 11]

#3


Use the list constructor, and append your items, like this:

使用列表构造函数,并附加您的项目,如下所示:

l = list ()
l.append ("foo")
l.append (3)
print (l)

gives me ['foo', 3], which should be what you want. See the documentation on list and the sequence type documentation.

给了我['foo',3],这应该是你想要的。请参阅列表文档和序列类型文档。

EDIT Updated

For inserting, use insert, like this:

要插入,请使用insert,如下所示:

l = list ()
l.append ("foo")
l.append (3)
l.insert (1, "new")
print (l)

which prints ['foo', 'new', 3]

打印['foo','new',3]

#4


http://diveintopython3.ep.io/native-datatypes.html#lists

You don't need to create empty lists with a specified length. You just add to them and query about their current length if needed.

您不需要创建具有指定长度的空列表。您只需添加它们并在需要时查询其当前长度。

What you can't do without preparing to catch an exception is to use a non existent index. Which is probably what you are used to in PHP.

如果不准备捕获异常,你不能做的就是使用不存在的索引。这可能是你在PHP中习惯的。

#5


You can use this syntax to create a list with n elements:

您可以使用此语法创建包含n个元素的列表:

lst = [0] * n

But be careful! The list will contain n copies of this object. If this object is mutable and you change one element, then all copies will be changed! In this case you should use:

不过要小心!该列表将包含此对象的n个副本。如果此对象是可变的并且您更改了一个元素,那么所有副本都将被更改!在这种情况下,您应该使用:

lst = [some_object() for i in xrange(n)]

Then you can access these elements:

然后你可以访问这些元素:

for i in xrange(n):
    lst[i] += 1

A Python list is comparable to a vector in other languages. It is a resizable array, not a linked list.

Python列表与其他语言中的矢量相当。它是一个可调整大小的数组,而不是链表。

#6


Sounds like what you need might be a dictionary rather than an array if you want to insert into specified indices.

如果要插入指定的索引,听起来你需要的可能是字典而不是数组。

dict = {'a': 1, 'b': 2, 'c': 3}
dict['a']

1

#7


I agree with ned that you probably need a dictionary for what you're trying to do. But here's a way to get a list of those lists of categories you can do this:

我同意你可能需要一本字典来表达你想要做的事情。但是这里有一种方法可以获得这些类别列表的列表:

lst = [list_of_categories.index(row["id"]) for row in rows]

#8


use a dictionary, because what you're really asking for is a structure you can access by arbitrary keys

使用字典,因为你真正要求的是一个你可以通过任意键访问的结构

list = {}

for row in rows:
  c = list_of_categories.index(row["id"])
  print c
  list[c] = row["name"]

Then you can iterate through the known contents with:

然后,您可以使用以下内容迭代已知内容:

for x in list.values():
  print x

Or check if something exists in the "list":

或者检查“列表”中是否存在某些内容:

if 3 in list: 
  print "it's there"

#9


I'm not sure if I understood what you mean or want to do, but it seems that you want a list which is dictonary-like where the index is the key. Even if I think, the usage of a dictonary would be a better choice, here's my answer: Got a problem - make an object:

我不确定我是否明白你的意思或想要做什么,但似乎你想要一个类似于dictonary的列表,其中索引是关键。即使我认为,使用dictonary将是一个更好的选择,这是我的答案:有问题 - 制作一个对象:

class MyList(UserList.UserList):

NO_ITEM = 'noitem'

def insertAt(self, item, index):

    length = len(self)
    if index < length:
        self[index] = item
    elif index == length:
        self.append(item)
    else:
        for i in range(0, index-length):
            self.append(self.NO_ITEM)
        self.append(item)

Maybe some errors in the python syntax (didn't check), but in principle it should work. Of course the else case works also for the elif, but I thought, it might be a little harder to read this way.

也许python语法中的一些错误(没有检查),但原则上它应该工作。当然,其他情况也适用于elif,但我想,这可能有点难以阅读。