可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
I have one record in a list
>>> bob =['bob smith',42,30000,'software']
I am trying to get the last name 'smith' from this record
I use the below command:
>>> bob[0].split()[1]
It provides me 'smith'
But the book I am referring to use the below command:
>>> bob[0].split()[-1]
it also gives me same result 'smith'
Why do indexes [1] and [-1] provide the same result?
回答1:
Python lists can be "back indexed" using negative indices. -1
signifies the last element, -2
signifies the second to last and so on. It just so happens that in your list of length 2, the last element is also the element at index 1
.
Your book suggests using -1
because it is more appropriate from a logical standpoint. You don't want the item at index 1
per se, but rather the last element of the list, which is the last name. What if, for example, a middle name was also included? Then using an index of 1
would not work whereas an index of -1
would.
回答2:
Because in this case the list you are splitting is ['adam', 'smith']
. So, bob[0].split()[1]
would return the 2nd element (don't forget list indexes are 0-based) and bob[0].split()[-1]
would return that last element.
Since the size of the list is 2, the second (index 1
) and last (index -1
) are the same.
In general if you have a list my_list
, then my_list[len(my_list) - 1] == my_list[-1]
回答3:
this is your input
In [73]: bob Out[73]: ['bob smith', 42, 30000, 'software']
this is what bob[0] gives you
In [74]: bob[0] Out[74]: 'bob smith'
as you can see bob[0] has only two elements so 1 give you second element and -1 gives you last element which is same
回答4:
Positive indexes count from the start of the list, negative indexes count from the end of the list.
That is:
bob[0].split()[0] == 'bob' bob[0].split()[1] == 'smith' bob[0].split()[-1] == 'smith' bob[0].split()[-2] == 'bob'
Now say you have someone with a middle name:
jane =['jane elizabeth smith', 42, 30000, 'software']
jane[0].split()[1]
would give Jane's middle name 'elizabeth'
, while jane[0].split()[-1]
would give her last name 'smith'
Now having said all this;
- do not assume a name is made up of two components
- do not assume a name is of the form <first name> <last name>
- do not assume a first name is one word
- do not assume a last name is one word
- do not assume anything!!!
For a more exhaustive list of things you might be wrong about see Falsehoods Programmers Believe About Names