开发者

Erase whole array Python

开发者 https://www.devze.com 2023-01-11 16:50 出处:网络
How do I erase a whole array, leaving it with no items? I want to do this so I can store new values in it (a new set of 100 floats) and find the minimum.

How do I erase a whole array, leaving it with no items?

I want to do this so I can store new values in it (a new set of 100 floats) and find the minimum.

Right now my program is reading the minimum from sets before I think because it is appending itself with the previous set still i开发者_JS百科n there. I use .append by the way.


Note that list and array are different classes. You can do:

del mylist[:]

This will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?).

Try:

a = [1,2]
b = a
a = []

and

a = [1,2]
b = a
del a[:]

Print a and b each time to see the difference.


It's simple:

array = []

will set array to be an empty list. (They're called lists in Python, by the way, not arrays)

If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.


Well yes arrays do exist, and no they're not different to lists when it comes to things like del and append:

>>> from array import array
>>> foo = array('i', range(5))
>>> foo
array('i', [0, 1, 2, 3, 4])
>>> del foo[:]
>>> foo
array('i')
>>> foo.append(42)
>>> foo
array('i', [42])
>>>

Differences worth noting: you need to specify the type when creating the array, and you save storage at the expense of extra time converting between the C type and the Python type when you do arr[i] = expression or arr.append(expression), and lvalue = arr[i]


Now to answer the question that perhaps you should have asked, like "I'm getting 100 floats form somewhere; do I need to put them in an array or list before I find the minimum?"

Answer: No, if somewhere is a iterable, instead of doing this:

temp = []
for x in somewhere:
   temp.append(x)
answer = min(temp)

you can do this:

answer = min(somewhere)

Example:

answer = min(float(line) for line in open('floats.txt'))
0

精彩评论

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