Python: single colon vs double colon

前端 未结 5 1301
醉梦人生
醉梦人生 2020-12-31 15:05

What is the difference between single and double colon in this situation? data[0:,4] vs data[0::,4]

women_only_stats = data[0::,4]         


        
相关标签:
5条回答
  • 2020-12-31 15:21

    Both syntaxes result in the same indexes.

    class Foo(object):
      def __getitem__(self, idx):
        print(idx)
    
    Foo()[1::,6]
    # prints (slice(1, None, None), 6)
    Foo()[1:,6]
    # prints (slice(1, None, None), 6)
    

    Basically, 1::,6 is a tuple of a slice (1::) and a number (6). The slice is of the form start:stop[:stride]. Leaving the stride blank (1::) or not stating it (1:) is equivalent.

    0 讨论(0)
  • 2020-12-31 15:24

    No, there is no difference.

    See the Python documentation for slice:

    From the docs: a[start:stop:step]

    The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default).

    In this case, you are including an empty step parameter.

    >>> a = [1,2,3,4]
    >>> a[2:]
    [3,4]
    >>> a[2::]
    [3,4]
    >>> a[2:] == a[2::]
    True
    

    And to understand what the step parameter actually does:

    >>> b = [1,2,3,4,5,6,7,8,9,10]
    >>> b[0::5]
    [1, 6]
    >>> b[1::5]
    [2, 7]
    

    So by leaving it to be implicitly None (i.e., by either a[2:] or a[2::]), you are not going to change the output of your code in any way.

    Hope this helps.

    0 讨论(0)
  • 2020-12-31 15:25

    It's like this: s[start:end:step]. Slice s from start to end with step step.

    0 讨论(0)
  • 2020-12-31 15:27

    In your case data is

    data = ['1' '0' '3' 'Braund, Mr. Owen Harris' 'male' '22' '1' '0' 'A/5 21171' '7.25' '' 'S']
    

    So it is equal to

    data = ['103Br.............7.25S']
    

    In this sitation there is only single item in list so data[0::4] or data[0:4] doesn't impact any thing.

    If you try this it will clear your question/answer

    print data[0][0::4]
    print data[0][0:4] 
    

    It works like

    data[start:end:step]
    

    So it behaves as usual if your step size is less then data length.

    0 讨论(0)
  • 2020-12-31 15:31

    There is no difference. You're indexing by an identical slice object.

    0 讨论(0)
提交回复
热议问题