Assigning Values to an Array with for Loop Python

不打扰是莪最后的温柔 提交于 2019-12-23 13:15:48

问题


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']

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)

at the end uuidArray should have these values [52, 22, 87]

and distArray should have these values [60, 90, 81]

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]


回答1:


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']




回答2:


When you define distArray as: 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.

There are two ways to deal with this:

  1. 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.
  2. Explicitly define an empty list. This can be done using something like: distArray = [0]*num_elements, where num_elements is the number of elements you want to have. This will create a list of size num_elements all equal to 0.



回答3:


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:

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.

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.

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)



回答4:


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


来源:https://stackoverflow.com/questions/27760831/assigning-values-to-an-array-with-for-loop-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!