【问题标题】:How to access distinct elements of a tuple inside an array, passed as function argument?如何访问数组中元组的不同元素,作为函数参数传递?
【发布时间】:2019-05-05 20:48:41
【问题描述】:

我正在尝试操作元组的不同元素,它是数组的一部分。

我有什么:

def my_function(lis):
  for i in lis:
    x[i], y[i], z[i] = lis[i]
  ...

我主要有:

my_function([(1,2,3), (4,5,6), (7,8,9), (10,11,12)]):
  ...

结果是:

TypeError: list indices must be integers or slices, not tuple

如前所述,我正在尝试从函数中访问元组的不同元素并对其进行操作。

【问题讨论】:

  • 这一行x[i], y[i], z[i] = lis[i]应该是x, y, z = i

标签: python arrays function tuples


【解决方案1】:

每个i 一个元组;你可能想要

for i in lis:
    x, y, z = i
    # use x, y, and z

或者干脆

for x, y, z in lis:
    # use x, y, and z

【讨论】:

  • Mybe 这太明显了,但当我试图实现这一点时,我不确定如何使用中间步骤。于是,我就想着把数据存成一个数组,比如:python x = y = z = [0] * len(lis) for i in lis: ind = 0 x[ind], y[ind], z[ind] = i ind += 1 这样是不是更方便的使用方式
猜你喜欢
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 2011-10-05
  • 2019-07-25
  • 1970-01-01
相关资源
最近更新 更多