Pregunta

def checkio(data):
   s1=[]
   s2=[]
   data.sort()
   for x in reversed(data[0:len(data):2]):
       s1.append(x)
   for y in reversed(data[0:(len(data)-1):2]):
       s2.append(y)
   print(s1, s2)

checkio([5, 8, 13, 27, 14])

If iteration over data[0:len(data):2] starts at item with the last index, why does the iteration over data[0:(len(data)-1):2] does not start at item with index just before the last?

¿Fue útil?

Solución

Reversed takes a list and reverses it.
The slicing notation iterates over the list and returns a new one.

When you call reversed on the slice (with or without stepping) of a list, the slice is created first, and then reversed.

For example, newL = reversed(L[0:len(L):2]) is the same as:

M = L[0:len(L):2]
newL = reversed(M)

Thus, when you say reversed(L[0:len(L)-1:2]), reversed is called on a list containing every other element in L, starting with the first, and excluding the last.

As a side note, L[::2] is the same as L[0:len(L):2], and L[:-1:2] is the same as L[0:len(L)-1:2]. Also, L[::-1] is L in reverse order.
This notation is very powerful.

If you want a checkio([5, 8, 13, 27, 14]) to return [14, 13, 5, 27, 8], then here are a few ways to do it:

>>> L = [5, 8, 13, 27, 14]
>>> L[::-2] + L[-2::-2]
[14, 13, 5, 27, 8]

>>> L = [5, 8, 13, 27, 14]
>>> list(reversed(L))[::2] + list(reversed(L))[1::2]
[14, 13, 5, 27, 8]

>>> L = [5, 8, 13, 27, 14]
>>> list(itertools.chain(itertools.islice(reversed(L), 0, len(L), 2), itertools.islice(reversed(L), 1, len(L), 2)))
[14, 13, 5, 27, 8]

Hope this helps

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top