lines = file('info.csv','r').readlines()
counts = []
for i in xrange(4):
counts.append(fromstring(lines[i][:-2],sep=',')[0:-1])
If anyone can explain this code to me, it would be greatly appreciated. I can't seem to find more advanced examples on slicing--only very simple on开发者_StackOverflow中文版es that don't explain this situation.
Thank you very much.
A slice takes the form o[start:stop:step]
, all of which are optional. start
defaults to 0
, the first index. stop
defaults to len(o)
, the closed upper bound on the indicies of the list. step
defaults to 1
, including every value of the list.
If you specify a negative value, it represents an offset from the end of the list. For example, [-1]
access the last element in a list, and -2
the second last.
If you enter a non-1
value for step, you will include different elements or include them in a different order. 2
would skip every other element. 3
would skip two out of every three. -1
would go backwards through the list.
[:-2]
Since start
is omitted, it defaults to the beginning of the list. A stop
of -2
indicates to exclude the last two elements. So o[:-2]
slices the list to exclude the last two elements.
[0:-1]
The 0
here is redundant, because it's what start would have defaulted to anyway. This is the same as the other slice, except that it only excludes the last element.
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 discusses them as well, when they were added to the language.
A good way to understand the slice syntax is to think of it as syntactic sugar for the equivalent for
loop. For example:
L[a:b:c]
Is equivalent to (e.g., in C):
for(int i = a; i < b; i += c) {
// slice contains L[i]
}
Where a
defaults to 0
, b
defaults to len(L)
, and c
defaults to 1
.
(And if c
, the step, is a negative number, then the default values of a
and b
are reversed. This gives a sensible result for L[::-1]
).
Then the only other thing you need to know is that, in Python, indexes "wrap around", so that L[-1]
signifies the last item in the list, L[-2]
is the second to last, and so forth.
If list
is a list then list[-1]
is the last element of the list, list[-2]
is the element before it and so on.
Also, list[a:b]
means the list with all elements in list
at positions between a
and b
. If one of them is missing, it is assumed to mean the end of the list. Thus, list[2:]
is the list of all elements starting from list[2]
. And list[:-2]
is the list of all elements from list[0]
to list[-2]
.
In your code, the [0:-1]
part it the same as [:-1]
.
精彩评论