擦除整个数组 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3499233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Erase whole array Python
提问by pjehyun
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.
我想这样做,以便我可以在其中存储新值(一组新的 100 个浮点数)并找到最小值。
Right now my program is reading the minimum from sets before I think because it is appending itself with the previous set still in there. I use .append by the way.
现在我的程序在我想之前从集合中读取最小值,因为它附加了前一个集合仍然在那里。顺便说一下,我使用 .append 。
采纳答案by Matthew Flaschen
Note that listand arrayare different classes. You can do:
请注意,list和array是不同的类。你可以做:
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?).
这实际上会修改您现有的列表。David 的回答创建了一个新列表并将其分配给相同的变量。您想要哪个取决于具体情况(例如,是否有任何其他变量引用同一列表?)。
Try:
尝试:
a = [1,2]
b = a
a = []
and
和
a = [1,2]
b = a
del a[:]
Print aand beach time to see the difference.
打印a和b每次查看差异。
回答by David Z
It's simple:
这很简单:
array = []
will set arrayto be an empty list. (They're called lists in Python, by the way, not arrays)
将设置array为一个空列表。(顺便说一下,它们在 Python 中称为列表,而不是数组)
If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.
如果这对您不起作用,请编辑您的问题以包含演示您的问题的代码示例。
回答by John Machin
Well yes arrays do exist, and no they're not different to lists when it comes to things like deland append:
嗯,是的数组确实存在,不,当涉及到del和这样的事情时,它们与列表没有什么不同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] = expressionor arr.append(expression), and lvalue = arr[i]
值得注意的区别:创建数组时需要指定类型,并且节省存储空间,代价是执行arr[i] = expressionor时在 C 类型和 Python 类型之间转换的额外时间arr.append(expression),以及lvalue = arr[i]
回答by John Machin
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?"
现在回答你可能应该问的问题,比如“我在某处得到 100 个浮点数;在找到最小值之前我是否需要将它们放入数组或列表中?”
Answer: No, if somewhereis a iterable, instead of doing this:
答:不,如果somewhere是可迭代的,而不是这样做:
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'))

