Python:A [1:]中x的含义是什么?

Mar*_*ham 8 python

当我发现这个时,我试图从维基百科中了解Kadane的算法:

def max_subarray(A):
    max_ending_here = max_so_far = A[0]
    for x in A[1:]:
        max_ending_here = max(x, max_ending_here + x)
        max_so_far = max(max_so_far, max_ending_here)
    return max_so_far
Run Code Online (Sandbox Code Playgroud)

我不熟悉Python.我尝试谷歌这种语法的作用,但我找不到正确的答案因为我不知道它叫什么.但是,我认为A[1:]相当于省略A[0],所以我认为for x in A[1:]:相当于for(int i = 1; i < A.length; i++)Java

但是,改变后for x in A[1:]:for x in range(1,len(A)),我得到了错误的结果

对不起,如果这是一个愚蠢的问题,但我不知道在哪里可以找到答案.有人可以告诉我这个语法是做什么的,它叫做什么?另外,你能给我相当于for x in A[1:]:Java吗?

Sau*_*nde 19

以下是我尝试过的一些示例

>>> a=[1,5,9,11,2,66]

>>> a[1:]
[5, 9, 11, 2, 66]

>>> a[:1]
[1]

>>> a[-1:]
[66]

>>> a[:-1]
[1, 5, 9, 11, 2]

>>> a[3]
11

>>> a[3:]
[11, 2, 66]

>>> a[:3]
[1, 5, 9]

>>> a[-3:]
[11, 2, 66]

>>> a[:-3]
[1, 5, 9]

>>> a[::1]
[1, 5, 9, 11, 2, 66]

>>> a[::-1]
[66, 2, 11, 9, 5, 1]

>>> a[1::]
[5, 9, 11, 2, 66]

>>> a[::-1]
[66, 2, 11, 9, 5, 1]

>>> a[::-2]
[66, 11, 5]

>>> a[2::]
[9, 11, 2, 66]
Run Code Online (Sandbox Code Playgroud)

我想你可以通过这个例子了解更多.


Pre*_*eti 7

这是数组切片语法.看到这个问题: 解释Python的切片表示法.

对于my_list对象列表,例如[1, 2, "foo", "bar"],my_list[1:]等同于从0索引开始的所有元素的浅复制列表1:[2, "foo", "bar"].所以你的for语句迭代这些对象:

for-iteration 0: x == 2 
for-iteration 1: x == "foo" 
for-iteration 2: x == "bar" 
Run Code Online (Sandbox Code Playgroud)

range(..) 返回索引的列表/生成器(整数),因此for语句将迭代整数 [1, 2, ..., len(my_list)]

for-iteration 0: x == 1 
for-iteration 1: x == 2
for-iteration 2: x == 3
Run Code Online (Sandbox Code Playgroud)

所以在后一个版本中你可以x用作列表的索引:iter_obj = my_list[x].

或者,如果您仍需要迭代索引(例如,对于当前对象的"计数"),则可以使用稍微更加pythonic的版本enumerate:

for (i, x) in enumerate(my_list[1:]):
    # i is the 0-based index into the truncated list [0, 1, 2]
    # x is the current object from the truncated list [2, "foo", "bar"]
Run Code Online (Sandbox Code Playgroud)

如果您决定将类型更改为其他类型,则此版本将更具未来性my_list,因为它不依赖于基于0的索引的实现细节,因此更有可能与支持切片语法的其他可迭代类型一起使用.