使用for Loop Python将值分配给数组 [英] Assigning Values to an Array with for Loop Python
问题描述
我试图将字符串的值分配给不同的数组索引
I'm trying to assign the values of a string to different array indexes
但是我遇到了一个错误,即列表分配超出范围 > p>
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=""
我尝试使用
distArray[i].append(distVal)
而不是
distArray[i]= distVal
但它给了错误,称为列表索引超出范围
but it gave an error called "list index out of range"
使用
distArray.append(distVal)
使其正常工作,但ou tcome是错误的
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
工作方式:
returnedList [ '52:33:42:40:94:10:19,-60' strong>, '22:34:42:24:89:70:89,-90', '87:77:98:54:81:23:71,-81' ]
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']
每次迭代都会将第一个字符分配给 uuidVal (例如:52、22、87)
和最后两个字符为 distVal (例如:60、90、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)
最后为 uuidArray 应该具有这些值 [52、22、87]
at the end uuidArray should have these values [52, 22, 87]
和 distArray 应该具有这些值 [ 60、90、81]
注意:使用 .append 连接值,例如如果与 distArray.append(distVal)等 distArray 一起使用,则值将类似于 [60,6090,609081]
Note: using .append concatenate the values, for example if used with distArray like distArray.append(distVal) the values will be like this [60, 6090, 609081]
推荐答案
是的,您将获得错误列表索引超出范围:
yes you will get error list index out of range for:
distArray[i] = distVal
访问尚未创建的索引
让我们看一下这个演示:
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
您的代码应如下所示:
uuidArray = []
distArray = []
distVal = ""
for beacon in returnedList:
uuidArray.append(beacon[:2])
distval += beacon[-2:]
distArray.append(distVal)
输出将为uudiArray:['52','22','87']和distArray:['60','6090','609081']
output will be uudiArray: ['52', '22', '87'] and distArray: ['60', '6090', '609081']
这篇关于使用for Loop Python将值分配给数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!