使用for循环Python将值赋给数组
|
我正在尝试将字符串的值分配给不同的数组索引
但我收到一个名为“列表分配超出范围”的错误 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 但它给出了一个错误,称为“列表索引超出范围” 运用 distArray.append(distVal) 使它工作没有错误,但结果是错误的 因为它会将新指定的值与下一个索引中的旧值连接起来 它应该如何工作: 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) 最后uuidArray应该有这些值[52,87] 和distArray应该有这些值[60,81] 注意:使用.append连接值,例如,如果与distArray一起使用,如distArray.append(distVal),则值将如下[60,6090,609081] 解决方法
是的,你会得到错误列表索引超出范围:
distArray[i] = distVal 您正在访问尚未创建的索引 让我们看看这个演示: >>> 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′] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
