Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print specific values from a multi-value element array in python

In python 3, I am trying to create an array of elements, where each element consists of two values. These values are not really key-value pairs because they are equally related to each other, meaning value 1 could be the key for value two, just as value two could be the key to value one and so I didn't think a dictionary was appropriate.

my_list = [ (VALUE1, OFFSET1), (VALUE2, OFFSET2) ]

def printList(list):
    for item in list:
        print(item)

How could I collect the VALUE and OFFSET "values" separately? Such as

theValue  = list[0].VALUE
theOffset = list[0].OFFSET

I'm thinking an array of structs perhaps?


2 Answers

You can use zip, which transposes the list and collects elements at the same position to one element in the result:

value, offset = zip(*my_list)

value
#('VALUE1', 'VALUE2')

offset
#('OFFSET1', 'OFFSET2')
like image 103
Psidom Avatar answered Mar 03 '26 07:03

Psidom


def printList(my_list):
    for item in my_list:
        print('Value ', item[0])
        print('Offset ', item[1])

The for loop iterates through my_list. Each element in the loop is received as tuple like (VALUE, OFFSET) in the variable item. So item[0] is VALUE and item[1] is OFFSET. And we print it.

like image 36
Arun Avatar answered Mar 03 '26 09:03

Arun