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 indexk
such thati <= 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 indexx
wherex = i + n*k, n >= 0
andi <= 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/