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?
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With