• Python翻转字符串或者列表的方式


    1. reversed

    class reversed(object)
     |  reversed(sequence) -> reverse iterator over values of the sequence
     |  
     |  Return a reverse iterator
     |  
     |  Methods defined here:
     |  
     |  __getattribute__(...)
     |      x.__getattribute__('name') <==> x.name
     |  
     |  __iter__(...)
     |      x.__iter__() <==> iter(x)
     |  
     |  __length_hint__(...)
     |      Private method returning an estimate of len(list(it)).
     |  
     |  next(...)
     |      x.next() -> the next value, or raise StopIteration
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  __new__ = <built-in method __new__ of type object>
     |      T.__new__(S, ...) -> a new object with type S, a subtype of T
    

    处理的对象是可迭代对象,返回值是一个迭代器,所以可以处理string list 等,如下:

    In [54]: reversed([1,2,3])                                                                                                                                                                        
    Out[54]: <listreverseiterator at 0x7f835810c190>
    
    In [55]: reversed('123')                                                                                                                                                                          
    Out[55]: <reversed at 0x7f835810c2d0>
    
    In [56]: type(reversed('123'))
    Out[56]: reversed
    
    In [57]: for i in reversed('123'):
       ....:     print i
       ....:     
    3
    2
    1
    

    PS: list内置__reversed__()方法实现的功能和此类似,使用方法见2

    2. reverse

    reverse是list内置的一个方法,所以只能对list使用,如下:

    In [62]: l = [1, 2, 3]                                                                                                                                                                            
    
    In [63]: l.reverse()
    
    In [64]: l
    Out[64]: [3, 2, 1]
    

    __reversed__()

    In [65]: l.__reversed__()
    Out[65]: <listreverseiterator at 0x7f835810ca90>
    
    In [66]: for i in l.__reversed__():                                                                                                                                                               
       ....:     print i
       ....:     
    1
    2
    3
    

    3. 切片

    最简单的一种方法了,可以对string和list使用

    In [73]: s
    Out[73]: 'i am a student.'
    
    In [74]: s[::-1]
    Out[74]: '.tneduts a ma i'
    
    In [75]: l
    Out[75]: [3, 2, 1]
    
    In [76]: l[::-1]
    Out[76]: [1, 2, 3]
    
  • 相关阅读:
    爬虫之JSON
    爬虫bs4案例
    爬虫bs4
    爬虫之Xpath案例
    爬虫之xpath
    监控 Kubernetes 集群应用
    手动部署k8s-prometheus
    ingress之tls和path使用
    ingress安装配置
    kube-dns和coreDNS的使用
  • 原文地址:https://www.cnblogs.com/wswang/p/5775942.html
Copyright © 2020-2023  润新知