Printing specific values ββfrom an array of elements with multiple values ββin python
In python 3, I am trying to create array
elements where each element has two values. These values ββare not really pairs key-value
, because they are equally related to each other, that is, value
1 can be key
for value
two, just as value
two can be from key
to value
one and so I did not think it fits dictionary
.
my_list = [ (VALUE1, OFFSET1), (VALUE2, OFFSET2) ]
def printList(list):
for item in list:
print(item)
How can I collect value
and OFFSET
"values"
separately? For example,
theValue = list[0].VALUE
theOffset = list[0].OFFSET
I think what array
structures can be?
source to share
def printList(my_list):
for item in my_list:
print('Value ', item[0])
print('Offset ', item[1])
The for loop repeats through my_list
. Each element in the loop is accepted as a tuple as (VALUE, OFFSET)
in a variable element. So, item[0]
- VALUE
, a item[1]
- OFFSET
. And we print it.
source to share
Since you have list
from tuples
and not:
theValue = list[0].VALUE
theOffset = list[0].OFFSET
You can use:
theValue = list[0][0]
theOffset = list[0][1]
So in for-loop
:
def printList(list):
for item in list:
print('VALUE: {}'.format(item[0]))
print('OFFSET: {}'.format(item[1]))
If you want to get all values ββat list
and offsets separately list
, you can use list-comprehension
:
values = [x[0] for x in list]
offsets = [x[1] for x in list]
Another important thing, AVOID using built-in
like functions list
as variables, uses something else instead.
source to share
I think namedtuple
can help you.
from collections import namedtuple
Element = namedtuple("Element", ["value", "offset"])
element_list = []
for value, offset in my_list:
element_list.append(Element(value, offset))
for element in element_list:
print element.value, element.offset
If you want to get all values ββand offsets separately, you can use numpy to convert mylist to numpy.array
, which is a 2d array.
import numpy as np 2d_array = np.array(my_list) values = 2d_array[:, 0] offsets = 2d_array[:, 1]
source to share