开发者

Arrays/dictionaries in python

I was trying to create a method that does a loop and in the process it creates array with 2 levels.

In PHP it would look like this

for($a = 0; $a < 3; $a++) {
    $something[$a] = [1,2,3];
}

But the problem is with python. I can't seem to add the key "u" to the variable and the array under it in the same time. How would you do this properly?

My current code:

for u in range(3):
    something[u] = [1,2,3] #this line doesn't seem to work
    somethingElse = [1,2,3] #开发者_如何学运维this works properly

Please excuse me if this is a stupid question. I am a beginner and I already tried googling it, but didn't actually find anything useful.


The best way to find information that you need is to use python tutorial. For example to answer your question yourself you can take a look at the following link: http://docs.python.org/tutorial/datastructures.html

You can use list comprehension:

something = [[1,2,3] for u in xrange(3)]

OR map:

something = map(lambda x: [1,2,3], xrange(3))

OR insert(if you need to insert into the exact index) or append to add item to the end of list:

something = [[1,2,3]]
something.append([1,2,3])# something == [[1,2,3],[1,2,3]]
something.insert(0, [2,3,1])# something == [[2,3,4],[1,2,3],[1,2,3]]

If you would like to use mappings(dictionary):

something = {}
for u in xrange(3):
   something[u] = [1,2,3]


It's easier when you forget all about PHP. You need to create an empty list first.

something = []
for u in range(3):
    something.append([1, 2, 3])

Note that something[u] won't work, because there is no u-th element in the list. Don't confuse lists (or arrays) with mappings.


You can't use an index within a list that doesn't exist.

something = []
for u in range(3):
    something.append([1, 2, 3])


You haven't populated that initial list yet.


It seems like what you actually want may be a dictionary, not a list.

something = {}
for u in range(3):
    something[u] = [1,2,3]

With a list, the list has to already have at least u elements before you can assign list[u], but with a dictionary you can add new items arbitrarily.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜