Найти - Пользователи
Полная версия: Python 3.0 Срезы списков
Начало » Python для новичков » Python 3.0 Срезы списков
1
PurplePenetrator
Драститя!!! Такая проблема. Прохожу тему Срезы списков ну и вижу такую схему. item… Тут то понятно что item-список start это начало среза, stop конец среза а вот что значит step?Объясните понятным языком. Сорян если тема уже была просто Я тут первый раз…

Копипаста Item - берёт срез от номера START, до STOP (не включая его), с шагом STEP. По умолчанию START = 0, STOP = длине объекта, STEP = 1. Соответственно, какие-нибудь (а возможно, и все) параметры могут быть опущены.
PEHDOM
а запустить интерпреторатор и самому посмореть как интерпретатор будет вести себя в той или иной ситуации?
 >>> a=[1,2,3,4,5,6,7,8,9,0]
>>> a[::1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
 >>> a[::2]
[1, 3, 5, 7, 9]
 >>> a[::3]
[1, 4, 7, 0]
 >>> a[::4]
[1, 5, 9]
 >>> a[::5]
[1, 6]
>>>
py.user.next
Здесь можешь прочитать про срезы (формулу
python.org. list
The slice of s from i to j with step k is defined as the sequence of items with index x =
i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k
and so on, stopping when j is reached (but never including j). When k is positive, i and j
are reduced to len(s) if they are greater. When k is negative, i and j are reduced to
len(s) - 1 if they are greater. If i or j are omitted or None, they become “end” values
(which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated
like 1.

Да и срезы можешь тренировать не на списках, а на строках.
  
>>> 'abcdef'
'abcdef'
>>> 'abcdef'[1:5:1]
'bcde'
>>> 'abcdef'[1:5:2]
'bd'
>>> 'abcdef'[1:5:-1]
''
>>> 'abcdef'[5:1:-1]
'fedc'
>>> 'abcdef'[5:1:-2]
'fd'
>>> 'abcdef'[::-1]
'fedcba'
>>> 'abcdef'[::-2]
'fdb'
>>>
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB