开发者

Integer array in Python

How I can define array of integer numbers in Python code

Say if this code is ok. o开发者_运维百科r no

pos = [int]

len = 99

for i in range (0,99):
    pos[i]=7


Why not just:

pos = [7] * 99

This is the most pythonic, in my opinion.


import array

pos = array.array('l', 7 * [99])

The array module of Python's standard library is the only way to make an array that comes with Python (the third-party module numpy offers other ways, but needs do be downloaded and installed separately) -- what your Q is doing, as well as every answer so far, is building a list, not an array.

In particular, there is no constraint that the pos list built in your Q and the several As contains just integers -- while, with the snippet I give, you do get that constraint (32-bit signed integers in this case, to be precise), which rigidly limits you but also saves a bunch of memory (an array of integers should take about one fifth the amount of memory that a list filled with integers will take, unless there's a lot of perennial duplication in the lists' items).

BTW, if you say array when you mean list (just in case list is what you meant), you're sure to cause a lot of confusion -- saying what you mean, and meaning what you say, helps a lot in clear communication, unsurprisingly!-)


you do not declare the type of variables in python, so no pos=[int] all you have to do:

pos=[]
for i in range(99):
    pos.append(7)


You can simply do

pos = [7] * 99
print pos #will print the whole array [7, 7, .... 7]


If you just want to declare the array, all you have to do in python is:

pos = []

If you want to fill the array with 99 7's:

pos = [7] * 99

If you want to fill the array based on a pattern:

pos = [i for i in range(99)]


One way is:

pos = [7 for _ in xrange(0,99)]

in Python 2 or:

pos = [7 for _ in range(0,99)]

in Python 3. These are list comprehensions, and are easy to extend for more complex work.

Also:

pos = [int]

doesn't make much sense. You're creating a list with the only element being the type int.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜