在本教程中,我们展示了如何反转Python序列。
当我们撤销项目时,我们改变了它们的顺序。请注意,不要将反转与降序排序相混淆。
Python列表有一个reverse函数。[::-1]切片操作反转Python序列。reversed内置函数返回一个反向迭代器。对象的__reversed__内置的reversed调用magic方法实现反向迭代。
Python反向列表
在第一个示例中,我们使用reverse方法和[::-1]运算符反转Python列表。
#!/usr/bin/python nums = [2, 7, 8, 9, 1, 0] nums.reverse() print(nums) rev_nums = nums[::-1] print(rev_nums)
reverse方法原地反转列表。nums[::-1]创建列表的新副本,其中元素被反转。
$ ./reverse_list.py [0, 1, 9, 8, 7, 2]
Python反转函数
reversed内置函数返回一个反向迭代器。
#!/usr/bin/python
words = ['forest', 'wood', 'sky', 'rock']
for word in reversed(words):
print(word)
word = 'forest'
for e in reversed(word):
print(e, end=' ')
print()
for e in reversed(range(1, 10, 2)):
print(e)
在示例中,我们对列表、单词和范围使用了reversed函数。
$ ./reversed_fun.py rock sky wood forest t s e r o f 9 7 5 3 1
Python自定义反转字符串函数
在下面的例子中,我们创建了一个自定义的字符串反转函数。
#!/usr/bin/python
def reverse_string(word):
rev = ''
n = len(word)
while n > 0:
n -= 1
rev += word[n]
return rev
word = 'forest'
print(reverse_string('forest'))
请注意,这是为了演示目的;这个实现很慢。
def reverse_string(word):
rev = ''
n = len(word)
while n > 0:
n -= 1
rev += word[n]
return rev
在函数中,我们使用while循环以相反的顺序构建新字符串。
Python__reversed__方法
__reversed__魔术方法实现应该返回一个新的迭代器对象,它以相反的顺序迭代容器中的所有对象。
#!/usr/bin/python
class Vowels(object):
def __init__(self):
self.vowels = ['a', 'e', 'i', 'o', 'u', 'y']
def __len__(self):
return len(self.vowels)
def __getitem__(self, e):
return self.vowels[e]
def __reversed__(self):
for e in self.vowels[::-1]:
yield elem
vowels = Vowels()
print('normal order:')
for vowel in vowels:
print(vowel, end=' ')
print()
print('reversed order:')
for vowel in reversed(vowels):
print(vowel, end=' ')
print()
在示例中,我们在Vowels对象中实现了__reversed__方法。
$ ./reversed_magic.py normal order: a e i o u y reversed order: y u o i e a
在本教程中,我们用Python完成了逆向操作。
阅读Python教程或列出所有Python教程。
