Skip to main content
 首页 » 编程设计

Python 语法/列表切片问题 : What does this syntax mean

2025年05月04日11zengkefu

lines = file('info.csv','r').readlines() 
 
counts = [] 
for i in xrange(4): 
    counts.append(fromstring(lines[i][:-2],sep=',')[0:-1]) 

如果有人能向我解释这段代码,将不胜感激。我似乎找不到关于切片的更高级示例——只有非常简单的示例,无法解释这种情况。

非常感谢。

请您参考如下方法:

切片采用 o[start:stop:step] 的形式,所有这些都是可选的。 start默认为 0 ,第一个指标。 stop默认为 len(o) ,列表索引的封闭上限。 step默认为 1 ,包括列表的每个值。

如果您指定一个负值,它表示距列表末尾的偏移量。例如,[-1]访问列表中的最后一个元素,以及 -2倒数第二个。

如果您输入非 1步骤的值,您将包括不同的元素或以不同的顺序包括它们。 2会跳过所有其他元素。 3会跳过每三个中的两个。 -1将向后遍历列表。

[:-2]

自 start被省略,它默认为列表的开头。 stop的 -2表示排除最后两个元素。所以o[:-2]对列表进行切片以排除最后两个元素。

[0:-1]

0这里是多余的,因为这是 start 无论如何都会默认的。这与另一个切片相同,只是它只排除了最后一个元素。

From the Data model page of the Python 2.7 docs :

Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j. When used as an expression, a slice is a sequence of the same type. This implies that the index set is renumbered so that it starts at 0.

Some sequences also support “extended slicing” with a third “step” parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i <= x < j.

The "what's new" section of the Python 2.3 documentation当它们被添加到语言中时,也会讨论它们。