abc = [0, ] * datalen;
"datalen
" is an Integer
.开发者_如何学JAVA
Then I see referencing like this:
abc[-1]
Any ideas?
creates a list with datalen
references to the object 0
:
>>> datalen = 10
>>> print [0,] * datalen
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
You don't really need the comma in there:
>>> print [0] * datalen
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
As everyone else has said, [0] * n will give you a list of n zeros, and indexing with negative numbers with a[-k] gives k-th element from the end, like:
a[-1]
gives the last element of the sequence and
a[-3]
gives the third last element of the sequence.
In addition to what has been said, remember that this behavior is expected when you are copying mutable objects. Classic trap for new python programmers
>>> bc = [0,] * 5
>>> bc
[0, 0, 0, 0, 0]
>>> bc[2]=4
>>> bc
[0, 0, 4, 0, 0]
>>> bb = [{}, ]*5
>>> bb
[{}, {}, {}, {}, {}]
>>> bb[2]["hello"]="hi"
>>> bb
[{'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}]
>>>
When used in this context, *
is the "sequence repetition" operator.
>>> datalen = 3
>>> abc = [0,] * datalen
[0, 0, 0]
In this case, it looks like it's being used as a way to create an array with datalen
elements, all of which are initialized to zero.
This works for strings too (since they are also sequences):
>>> 'String' * 3
'StringStringString'
creates a list with datalen number of zeroes
>>> datalen=5
>>> abc = [0, ] * datalen
>>> abc
[0, 0, 0, 0, 0]
精彩评论