简体   繁体   中英

Filling a list inside a for loop in python

I am trying to make a vector out of two different ones as shown in the piece of code below. However, I get a list out of range exception on the 5th line the first time the code goes in the for loop.

What am I doing wrong?

def get_two_dimensional_vector(speeds, directions):
    vector = []
    for i in range(10):
        if (i % 2 == 0):
            vector[i/2][0] = speeds[i/2]
        else :
            vector[i/2 - 1/2][1] = directions[i/2 - 1/2]

You can't use a Python list this way. It's not like a C array with a predefined length. If you want to add a new element, you have to use the append method or something.

Aside from that, you're also using a second index, implying that the elements of vector are themselves lists or dicts or something, before they've even been assigned.

It looks like you want to convert speeds and directions to a two-dimensional list. So, first, here's how to do that with a loop. Note that I've removed the fixed-size assumption you were using, though the code still assumes that speeds and directions are the same size.

def get_two_dimensional_vector(speeds, directions):
    vector = []
    for i in range(len(speeds)):
        vector.append([speeds[i], directions[i]])
    return vector

speeds = [1, 2, 3]
directions = [4, 5, 6]

v = get_two_dimensional_vector(speeds, directions)
print(v)

Now, the Pythonic way to do it.

print(zip(speeds, directions))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM