当前位置: 动力学知识库 > 问答 > 编程问答 >

append tuples to array in groups python

问题描述:

I'm trying to append tuples to my array in groups. The number of groups or the number of tuples in each group is unknown.

I'm aware there should be a very simple answer for this, but my mind is grasped on swift, which takes care of this issue for me.

This is my issue, I need to be able to do this:

array = []

array[0].append([1, 2]) # error because there isn't a '0' index

array[0].append([7, 2])

array[0].append([89, -5])

array[1].append([2, 3])

so I don't get the wrong kind of responses of why I'm not doing it another way I made a simple program to illustrate the point of why I need it to work like this.

def get_data(index, array):

# loop for an un-determined number of times, calculates differently depending on the index

one_or_more = 4

for i in range(0, one_or_more):

# do some calculations depending on index, which should differ for each loop

data1 = index * 3 + i

data2 = index * 4 + i

array.append([data1, data2])

def main():

array = []

array_index = 0

some_num = "110, 121, 122, 123, 124, 125, 130, 131, 323, 324, 325, 326, 340, 341, 342, 343".strip().split(", ")

for i in some_num:

get_data(int(i), array[array_index]) # error here with 'array[array_index]', because I can't index array with '0' because it's not initialized yet

array_index += 1

if __name__ == "__main__":main()

网友答案:

The value at a given index is being over written. So, an array is not a suitable data structure for your task. I would use a defaultdict.

from collections import defaultdict

key_lists = defaultdict(list)
key_lists[0].append([1,2])
key_lists[0].append([89, -5])
key_lists[1].append([2, 3])

print(key_lists)
print(key_lists[0])

one_or_more = 4

for i in range(0, one_or_more):
    data1 = index * 3 + i
    data2 = index * 4 + i
    key_lists[i].append([data1, data2]
分享给朋友:
您可能感兴趣的文章:
随机阅读: