简体   繁体   English

如何在Python中创建类似PHP的列表?

[英]How do you create a list like PHP's in Python?

This is an incredibly simple question (I'm new to Python). 这是一个非常简单的问题(我是Python的新手)。

I basically want a data structure like a PHP array -- ie, 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. 当我将项目添加到列表中时,我不想按顺序放置它们,而是想将它们插入列表中的指定插槽中。

Ie, 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"]

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. PHP数组更像Python字典,而不像Python列表。 For example, they can have strings for keys. 例如,它们可以具有用于键的字符串。

And confusingly, Python has an array module, which is described as "efficient arrays of numeric values", which is definitely not what you want. 令人困惑的是,Python有一个数组模块,它被描述为“有效的数值数组”,这绝对不是您想要的。

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]

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. 给我['foo', 3] ,这应该是您想要的。 See the documentation on list and the sequence type documentation . 请参阅清单中文档序列类型文档

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]

http://diveintopython3.ep.io/native-datatypes.html#lists 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中所习惯的。

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. 该列表将包含该对象的n副本。 If this object is mutable and you change one element, then all copies will be changed! 如果该对象是可变的,并且您更改了一个元素,则所有副本都将被更改! In this case you should use: 在这种情况下,您应该使用:

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. Python列表可与其他语言中的向量媲美。 It is a resizable array, not a linked list. 它是可调整大小的数组,而不是链接列表。

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 1个

I agree with ned that you probably need a dictionary for what you're trying to do. 我同意ned的观点,您可能需要一本字典来尝试做。 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]

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"

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: 即使我认为,使用字典式字典是一个更好的选择,这是我的答案:有问题-创建一个对象:

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. 也许python语法有一些错误(没有检查),但原则上应该可以。 Of course the else case works also for the elif, but I thought, it might be a little harder to read this way. 当然,else的else情况也适用,但是我认为,以这种方式阅读可能会有点困难。

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

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