使用for循环Python将值赋给数组

AMS*_*S91 4 python arrays for-loop variable-assignment

我正在尝试将字符串的值分配给不同的数组索引

但我收到一个名为"列表分配超出范围"的错误

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=""
Run Code Online (Sandbox Code Playgroud)

我试过用

distArray[i].append(distVal)
Run Code Online (Sandbox Code Playgroud)

代替

distArray[i]= distVal
Run Code Online (Sandbox Code Playgroud)

但它给出了一个错误,称为"列表索引超出范围"

运用

distArray.append(distVal)
Run Code Online (Sandbox Code Playgroud)

使它工作没有错误,但结果是错误的

因为它会将新指定的值与下一个索引中的旧值连接起来

它应该如何工作:

returnList [ '52:33:42:40:94:10:19,-60','22:34:42:24:89:70:89,-90',' 87:77:98:54:81 :23:71,-81' ]

每次迭代时,它将第一个字符分配给char给uuidVal(例如:52,22,87),最后两个字符分配给distVal(例如:60,90,81)

最后uuidArray应该有这些值[ 52,22,87 ]

distArray应该有这些值[ 60,90,81 ]

注意:使用.append连接值,例如,如果与distArray 一起使用,如distArray.append(distVal),则值将如下[60,6090,609081]

Hac*_*lic 8

是的,你会得到错误列表索引超出范围:

distArray[i] = distVal
Run Code Online (Sandbox Code Playgroud)

您正在访问尚未创建的索引

让我们看看这个演示:

>>> 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
Run Code Online (Sandbox Code Playgroud)

你的代码应该是这样的:

uuidArray = []
distArray = []
distVal = ""
for beacon in returnedList:
        uuidArray.append(beacon[:2])
        distval += beacon[-2:]
        distArray.append(distVal)
Run Code Online (Sandbox Code Playgroud)

输出将是uudiArray:['52','22','87']和distArray:['60','6090','609081']