[英]Negative Indexing & Slicing Python
Long time reader first time poster, ever.长期读者第一次海报,永远。
I am trying to understand all I can about indexing, slicing, negative indexing, etc. with lists.我试图了解所有关于列表的索引、切片、负索引等。
If I have a list:如果我有一个列表:
toeFriendly_terms=['feet', 'shoes', 'socks', 'sandals', 'boots', 'toe rings']
Ask 1: I would like to print() this list in reverse.问 1:我想反向打印()这个列表。
Q: Is it possible to use negative indexing to do this?问:是否可以使用负索引来做到这一点? Q: If so, how?
问:如果是这样,怎么办? Q: If not, what is the proper way to do this?
问:如果不是,正确的做法是什么? Q: If you can do it but there is a better way how do you do it?
问:如果你能做到,但有更好的方法,你会怎么做?
Ask 2: I looked around on here and found the.reverse() function but this opened up more questions.问 2:我在这里四处寻找并找到了 .reverse() 函数,但这引发了更多问题。
names=['fanny', 'david', 'jimmy', 'hwang', 'esther']
#first three - fanny, david and jimmy
print('1. ', names[0:3])#stops right before 3 to give just what you need
#last three
print('2. ', names[2:])#did not designate an end because I wanted all of it to come through
print('3. ', names[:-1]) #calls right up to before -1
names2=names.reverse() #still affects the original list
print('4. ',names )
Q: Is there any way to preserve the original list so the reverse function doesn't affect whatever other work I've been doing with the list?问:有什么方法可以保留原始列表,以便反向功能不会影响我对列表所做的任何其他工作? (I am very new so I still do not fully understand if just duplicating the list is way easier or even more efficient..)
(我很新,所以我仍然不完全理解是否只是复制列表更容易或更有效..)
Q: What kind of real-world, 'on the job' applications does.reverse() have?问:.reverse() 有什么样的现实世界的“在职”应用程序?
Thanks.谢谢。 That is all for now.
现在就这些了。
You are right in that calling some_list.reverse()
mutates the original list, which you might expect or not (if not, keep reading).你是对的,因为调用
some_list.reverse()
会改变原始列表,你可能期望或不期望(如果不是,请继续阅读)。
You can use slicing to reverse the list like this: some_list[::-1]
.您可以使用切片来反转列表,如下所示:
some_list[::-1]
。
Note that there is always the reversed()
method, which returns an iterator.请注意,始终存在
reversed()
方法,它返回一个迭代器。 If you want to get the reversed list all at once, you can just (surprise) turn it into a list: list(reversed(some_list))
.如果你想一次获得所有的反向列表,你可以(惊讶地)把它变成一个列表:
list(reversed(some_list))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.