繁体   English   中英

用于向量数据结构中的向量的 Python

[英]Python for vector in vector data structure

我想定义一个二维数组,其中每个元素的第二维是一个如下所示的数组:

[5] [x, y, z]
[1] [a]
[8] [b, c, d, e]
...

在第一维中查找数字并将项目添加到其中的代码是

stream = [[], []]
for i in range( 0, line_count ):
    num = arr1[ i ]
    item = arr2[ i ]
    found = 0
    
    # stream is empty in the beginning
    if len( stream ) == 0:
        stream.append( num )

    # stream is non-empty
    for j in range( 0, len(stream) ):
        if num in stream[ j ]:
           idx = stream.index( num )
           stream[ idx ].append( item )
           found = 1
           break

    # stream is not empty and we didn't find num
    if found == 0:
        stream.append( num )
        stream[ len(stream)-1 ].append( item )

但是,我收到此错误:

    stream[ len(stream)-1 ].append( item )
AttributeError: 'str' object has no attribute 'append'

尽管我猜stream = [[], []]已被定义为二维数组stream = [[], []]但似乎我没有正确定义 vector 中的向量? 那我怎么定义这样的事情呢?

最后一个元素stream[ len(stream)-1 ]不是一个列表,因为当你执行stream.append( num )stream列表变成[ [], [], num ]
如果我理解正确,您正在尝试执行stream = [ [5, [x, y, z]], [1, [a]]...] 如果是这样,以下代码可能有效:

if found == 0:
        stream.append( [num] ) # Append as a list contains num as element
        stream[ len(stream)-1 ].append( item )

对于更pythonic的方式,您还可以使用:

if found == 0:
        stream.append( [num] ) # Append as a list contains num as element
        stream[-1].append( item ) # -1 means the last index

如果要将每个num映射到特定array ,也可以使用 Dictionary 。

暂无
暂无

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

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