Python reversed function and usage

In some cases, the program needs to reverse traversal, this time by the reversed () function, which may receive various sequence (tuple list, interval, etc.) parameters, and then returns a "reverse order" in France on behalf of the device, this function has no effect on the parameter itself.

In an interactive interpreter, the function test process is as follows:

>>> a = range(10)
>>> [x for x in reversed(a)]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

  

As seen from the above code, via the reversed () function to get the range (10) of the inverted sequence; if a visit again, and will not see a change:

>>> a
range(0, 10)


the reversed () may of course be inverted list, tuples. Test code, for example, as follows:

>>> b = ['a', 'fkit', 20, 3.4, 50]
>>> [x for x in reversed(b)]
[50, 04/03, 20 'fkit', 'a']

  

As mentioned earlier, str sequence actually, it can also be achieved by this function without affecting the string itself, the string in reverse order traversal. Test code, for example, as follows:

>>> c = 'Hello,Charlie'
>>> [x for x in reversed(c)]
['e', 'i', 'l', 'r', 'a', 'h', 'C', ',', 'o', 'l', 'l', 'e', 'H']

  

Guess you like

Origin www.cnblogs.com/daniumiqi/p/12106879.html