【问题标题】:Access specific entries in a python tuple访问 python 元组中的特定条目
【发布时间】:2020-05-17 19:33:18
【问题描述】:

在 python 元组中,我想访问第一个条目。我可以通过写作来做到这一点:

example_tuple[0]

现在第一个条目是一个浮点数组。从这个数组中,我想获取除最后一个之外的所有条目。就像描述的here 一样,我是这样写的:

example_array[:-1]

现在我想把这两个特性叠加起来,我用下面的命令试了一下:

example_tuple[0[:-1]]

这会产生以下错误:

TypeError: 'int' object is not subscriptable

我不确定出了什么问题,因为其中没有涉及整数。

【问题讨论】:

  • 试试example_tuple[0][:-1]
  • @ShubhamShaswat 是的。这对我来说很完美。谢谢。

标签: python tuples


【解决方案1】:

通过输入:

example_tuple[0[:-1]]

Python 首先尝试计算括号内的内容,即0[:-1]。这解释了错误:

TypeError: 'int' object is not subscriptable

您正在尝试以数组形式访问 0

正如@ShubhamShaswat 所说,要访问数组中的数组,您需要获取第一个数组,并访问您想要的值:

example_tuple = [[5.7, 2.9, 7.9], [0.1, 4.2], [1.2]]

### Using 2 steps ###
# temp_var equals [5.7, 2.9, 7.9]
temp_var = example_tuple[0]
# output: [5.7, 2.9]
print(temp_var[:-1])

### Which can be shortened in Python by assembling array access ###
# output: [5.7, 2.9]
print(example_tuple[0][:-1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-16
    • 2021-11-14
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2018-05-18
    • 1970-01-01
    相关资源
    最近更新 更多