简体   繁体   English

在python中的for循环内填充列表

[英]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. 但是,当代码第一次进入for循环时,我在第5行获得了超出范围的异常列表。

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. 您不能以这种方式使用Python列表。 It's not like a C array with a predefined length. 它不像具有预定义长度的C数组。 If you want to add a new element, you have to use the append method or something. 如果要添加新元素,则必须使用append方法或其他方法。

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. 除此之外,您还使用了第二个索引,这意味着vector的元素本身甚至在被分配之前就是列表或字典或其他内容。

It looks like you want to convert speeds and directions to a two-dimensional list. 看来您想将speedsdirections转换为二维列表。 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. 请注意,尽管代码仍然假定speedsdirections相同,但我已经删除了您使用的固定尺寸假设。

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. 现在,用Python的方式做到这一点。

print(zip(speeds, directions))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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