Timk10
Timk10

Reputation: 191

Fill two separate arrays with data?

I am trying to fill two separate arrays in Python, one will contain the value numbers, and the other will be the weight. The array is as follows

res = [2, 3, 72, 17, 44, 23, 31, 24, 1, 26]

Basically the 3 indicates that there will be 3 sets of items, where val should = 72, 44, and 31 and wt should = 17, 23, and 24. How do I fill two separate array variables with these figures? Here is what I have so far but I think I'm overthinking it.

nCount = 1

N = res[1]

val = []

wt = []

while nCount < N * 2:
    for x in range(N):
        val = res[nCount + 1]
        print(val)

    for y in range(N):
        wt = res[nCount + 2]
        print(wt)
        nCount += 2

Upvotes: 0

Views: 46

Answers (2)

ingvar
ingvar

Reputation: 4377

You can use slices to get your arrays:

items_count = res[1]
values = res[2:2 + items_count * 2:2]
weights = res[3:3 + items_count * 2:2]

res[2:2 + items_count * 2:2] means select each 2 element from res starting from element with index 2 to element with index 2 + items_count * 2. You can read more about slices here.

Upvotes: 1

Lingaraj Gowdar
Lingaraj Gowdar

Reputation: 19

Using len(list)

res[2:len(res)-2:2]

res[3:len(res)-2:2] or res[3:len(res)-1:2]

Upvotes: 0

Related Questions