使用 for 循环 Python 为数组赋值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27760831/
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
Assigning Values to an Array with for Loop Python
提问by AMS91
I'm trying to assign the values of a string to different array indexes
我正在尝试将字符串的值分配给不同的数组索引
but I'm getting an error called "list assignment out of range"
但我收到一个错误,称为“列表分配超出范围”
uuidVal = ""
distVal = ""
uuidArray = []
distArray = []
for i in range(len(returnedList)):
for beacon in returnedList:
uuidVal= uuidVal+beacon[:+2]
uuidArray[i]= uuidVal
distVal= distVal+beacon[-2:]
distArray[i]= distVal
uuidVal=""
disVal=""
I tried using
我尝试使用
distArray[i].append(distVal)
instead of
代替
distArray[i]= distVal
but it gave an error called "list index out of range"
但它给出了一个名为“列表索引超出范围”的错误
Using
使用
distArray.append(distVal)
made it work with no error but the outcome was wrong
使它正常工作,但结果是错误的
because it keep concatenating the new assigned value with old values in the next index
因为它不断将新分配的值与下一个索引中的旧值连接起来
How it should work:
它应该如何工作:
returnedList['52:33:42:40:94:10:19, -60', '22:34:42:24:89:70:89, -90', '87:77:98:54:81:23:71, -81']
返回列表[ '52:33:42:40:94:10:19, -60', '22:34:42:24:89:70:89, -90', '87:77:98:54:81 :23:71, -81']
with each iteration it assign the first to char to uuidVal(ex: 52, 22, 87) and the last two char to distVal(ex: 60, 90, 81)
每次迭代时,它将第一个字符分配给uuidVal(例如:52、22、87),将最后两个字符分配给distVal(例如:60、90、81)
at the end uuidArrayshould have these values [52, 22, 87]
最后uuidArray应该有这些值[52, 22, 87]
and distArrayshould have these values [60, 90, 81]
和distArray应该有这些值[60, 90, 81]
Note:using .appendconcatenate the values, for example if used with distArraylike distArray.append(distVal)the values will be like this [60, 6090, 609081]
注意:使用.append连接值,例如,如果与distArray一起使用,如distArray.append(distVal),则值将是这样的[60, 6090, 609081]
采纳答案by Hackaholic
yes you will get error list index out of range for:
是的,您将获得超出范围的错误列表索引:
distArray[i] = distVal
you are accessing the index that is not created yet
您正在访问尚未创建的索引
lets see this demo:
让我们看看这个演示:
>>> a=[] # my list is empty
>>> a[2] # i am trying to access the value at index 2, its actually not present
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
your code should be like this:
你的代码应该是这样的:
uuidArray = []
distArray = []
distVal = ""
for beacon in returnedList:
uuidArray.append(beacon[:2])
distval += beacon[-2:]
distArray.append(distVal)
output will be uudiArray: ['52', '22', '87'] and distArray: ['60', '6090', '609081']
输出将是 uudiArray: ['52', '22', '87'] 和 distArray: ['60', '6090', '609081']
回答by dave
When you define distArray as:
distArray = []
当您将 distArray 定义为:
distArray = []
You are initializing a list with 0 elements, so distArray[2]
will correctly throw an error, since you are attempting to access an element past the total length of the array.
您正在用 0 个元素初始化一个列表,因此distArray[2]
会正确地抛出错误,因为您试图访问超过数组总长度的元素。
There are two ways to deal with this:
有两种方法可以解决这个问题:
- Use
append
. This takes the list and extends it by the element contained in the function call. This is to be preferred for all but the rarest of occasions, imo. - Explicitly define an empty list. This can be done using something like:
distArray = [0]*num_elements
, wherenum_elements
is the number of elements you want to have. This will create a list of sizenum_elements
all equal to 0.
- 使用
append
. 这获取列表并通过函数调用中包含的元素扩展它。除了最罕见的情况外,这在所有情况下都是首选,imo。 - 显式定义一个空列表。这可以使用以下内容来完成:
distArray = [0]*num_elements
,num_elements
您想要拥有的元素数量在哪里。这将创建一个大小num_elements
都等于 0的列表。
回答by Eli Korvigo
Others have already explained the mistake, so I'll just leave my 2c on how to work this out. First of all you can use pure Python:
其他人已经解释了这个错误,所以我将把我的 2c 留在如何解决这个问题上。首先,您可以使用纯 Python:
distArray = [None for _ in xrange(max_value+1)]
I'm using None-type objects to allocate the array (whereas many people prefer zeros) because they can't be interpreted as an integer or bool.
我使用 None 类型的对象来分配数组(而许多人更喜欢零),因为它们不能被解释为整数或布尔值。
If your process is going to be RAM-intensive, you should better use numpy arrays. And there is a highly efficient way to create an empty array in numpy.
如果您的进程将占用大量内存,则最好使用 numpy 数组。并且有一种高效的方法可以在 numpy 中创建一个空数组。
import numpy as np
distArray = np.empty(max_value+1, dtype=str)
Notice that you should manually select a data type.
请注意,您应该手动选择数据类型。
What you are trying to achieve is basically a simplified hash-map/table. If you're not sure about the maximum value, you can consider writing your own 'dynamic' array, that will increase in size, if called outside its borders, instead of raising the error.
您想要实现的基本上是一个简化的哈希映射/表。如果您不确定最大值,您可以考虑编写自己的“动态”数组,如果在其边界外调用,则大小会增加,而不是引发错误。
class DistArray():
def __init__(self, starting_size):
self.arr = [None for _ in xrange(starting_size)]
def __getitem__(self, i):
return self.arr[i]
def __iter__(self):
return iter(self.arr)
def insert_item(self, item, value):
try:
self.arr[value] = item
except:
self.arr.extend([None for _ in xrange(value - len(self.arr))])
self.arr[value] = item
This thing will adapt to your needs.
这个东西会适应你的需求。
distArray = DistArray(starting_size)
distArray.insert_item(string, value)
回答by Tanuja Shelke
def array():
a = []
size = int(input("Enter the size of array: "))
for i in range(size):
b = int(input("enter array element: "))
a.append(b)
return a