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

标签 python list delimiter slice

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当它们被添加到语言中时,也会讨论它们。

关于Python 语法/列表切片问题 : What does this syntax mean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6868941/

相关文章:

function - Delphi SAP SAPFunctions DELIMITER 突然被忽略?

Java - 如果单词以用户输入的定界符结尾,则执行 x

python - conda env 无法创建新环境

python - 我收到此 ValueError : total size of new array must be unchanged error. 任何人都可以解决吗?

python - 在Python中调用select

c++ - 如何返回列表中指针的值?

python - 将字符串列表转换为日期时间

ruby - 用于构建列表的 elisp 数据结构/工作流程

c# - 构建列表中项目计数的字典

R:如何通过仅比较每个字符串中的前 3 个制表符分隔项来对两个字符串向量使用 setdiff?不使用 qdap