简体   繁体   中英

Python for vector in vector data structure

I want to define a 2D array where the second dimension for each element is an array like below:

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

The code for finding the number in the first dimension and adding item to that is

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 )

However, I get this error:

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

It seems that I didn't define a vector in vector properly although I guess stream = [[], []] has been defined as 2D array? How can I define such thing then?

The last element stream[ len(stream)-1 ] is not a list, because when you do stream.append( num ) , the stream list becomes [ [], [], num ] .
If I understand correctly, you are trying to do stream = [ [5, [x, y, z]], [1, [a]]...] . If so, the following code might work:

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

For a more pythonic way, you can also use:

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

You can also use Dictionary, if you want to map each num to a specific array .

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