python中实现列表元素的永久反转和临时反转

 

>>> test1 = ["sss","ccc","aaa","ddd"]
>>> test1.reverse()   ## 就地反转
>>> test1
['ddd', 'aaa', 'ccc', 'sss']
>>> test1.reverse()
>>> test1
['sss', 'ccc', 'aaa', 'ddd']
>>> reversed(test1)   ## 临时反转
<list_reverseiterator object at 0x00000152727139D0>
>>> test1
['sss', 'ccc', 'aaa', 'ddd']
>>> test2 = reversed(test1)
>>> test2
<list_reverseiterator object at 0x00000152727139D0>
>>> type(test2)
<class 'list_reverseiterator'>
>>> for i in test2:
    print(i,end=",")

    
ddd,aaa,ccc,sss,
>>> for i in test2:   ## test2只能迭代一次
    print(i,end=",")

    
>>> for i in test2:
    print(i,end=",")

    
>>> for i in reversed(test1):
    print(i,end=",")

    
ddd,aaa,ccc,sss,
>>> for i in reversed(test1):
    print(i,end=",")

    
ddd,aaa,ccc,sss,
>>> for i in reversed(test1):
    print(i,end="_")

    
ddd_aaa_ccc_sss_

 

posted @ 2020-12-26 14:18  小鲨鱼2018  阅读(275)  评论(0编辑  收藏  举报