[英]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.