从 python 中的多值元素数组打印特定值

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

在 python 3 中,我试图创建一个 array 元素,其中每个元素包含两个值。这些值并不是真正的 key-value 对,因为它们彼此之间的相关性相同,这意味着 value 1 可能是 value 两个的 key,就像 value两个可能是 keyvalue 一个,所以我认为 dictionary 不合适。

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

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

如何分别收集VALUEOFFSET"values"?如

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

我在考虑 array 结构?

您可以使用zip,它将列表转置并将相同位置的元素收集到结果中的一个元素:

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])

for 循环遍历 my_list。循环中的每个元素都作为元组接收,例如变量项中的 (VALUE, OFFSET) 。所以 item[0]VALUEitem[1]OFFSET。然后我们打印出来。

我会这样做:

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'])

由于您的 listtuples,而不是:

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

您可以使用:

theValue = list[0][0]
theOffset = list[0][1]

所以在你的 for-loop:

def printList(list):
    for item in list:
        print('VALUE: {}'.format(item[0]))
        print('OFFSET: {}'.format(item[1]))

如果你想获取list中的所有值和单独的list中的偏移量,你可以使用list-comprehension:

values = [x[0] for x in list]
offsets = [x[1] for x in list]

还有一件更重要的事情,避免 使用 built-in 函数,如 list 作为变量,改用其他东西。

尝试使用 list comprehension

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

我觉得namedtuple可以帮到你。

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

如果你想分别获取所有的值和偏移量,你可以使用numpy将my_list转换为numpy.array,这是一个二维数组。

import numpy as np

2d_array = np.array(my_list)

values = 2d_array[:, 0]
offsets = 2d_array[:, 1]