简体   繁体   English

简单的 Python 代码段/错误

[英]Trivial Python Snippet/Error

He defines the following Python function normally:他通常定义以下Python函数:

def findMax (team, board, MIN, MAX, levels)
    ...
    ...
    return

In his program he calls it this way:在他的程序中,他这样称呼它:

myValue = findMax(team, board, MIN, MAX, 3) [1]

and it works properly.它工作正常。 But if I remove the bracketed 1 and call it like this:但是,如果我删除括号中的 1 并像这样调用它:

myValue = findMax(team, board, MIN, MAX, 3)

it throws this error:它抛出这个错误:

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

My question is this: What is the bracketed 1 doing?我的问题是:括号中的 1 在做什么? I have never seen a bracketed number following arguments in a called function and I can't find the answer anywhere in the Python literature.我从未在被调用函数中的参数后面看到括号中的数字,而且我在 Python 文献中的任何地方都找不到答案。

[1] is a subscription expression . [1]订阅表达式 findMax() returns a list , and [1] picks out a single element from that sequence, the one with index 1. findMax()返回一个列表[1]从该序列中选出一个元素,即索引为 1 的元素。

When you remove the [1] expression, you get the TypeError later on when code that expected a different type of object, but is now given that list instead.当您删除[1]表达式时,稍后您会在需要不同类型对象的代码时收到TypeError ,但现在改为提供该列表。

Perhaps you found the space between the ) of the findMax() call and the [1] confusing.也许你发现之间的空间)中的findMax()调用和[1]混淆。 It is much better to leave out that space, and the Python style guide states no spaces should be used there, but spaces are perfectly legal there:最好省略那个空格, Python 风格指南指出不应在那里使用空格,但空格在那里是完全合法的:

>>> l = ['foo', 'bar']
>>> l[1]
'bar'
>>> l [1]
'bar'
>>> l             [1]
'bar'

Legal, but confusing to new coders.合法,但对新编码人员来说很困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM