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?

+3


source to share


6 answers


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.

+1


source


You can use zip

that wraps the list and collects items in one position with one item in the result:



value, offset = zip(*my_list)

value
#('VALUE1', 'VALUE2')

offset
#('OFFSET1', 'OFFSET2')

      

+2


source


I will do it like this:

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

def printList(my_llst):
  values = []
  ofts = []
  for item in my_llst:
      values.append(item[0])
      ofts.append(item[1])
  return (values,ofts)

      

(['VALUE1', 'VALUE2'], ['OFFSET1', 'OFFSET2'])

0


source


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.

0


source


Try to use understanding

theValue  = [value[0] for value in my_list] 
theOffset = [offset[0] for value in offset]

      

0


source


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]

      

0


source







All Articles