Slicing

作者: bin_guo | 来源:发表于2018-09-10 11:45 被阅读0次

    Slicing list

    Slicing like this? No!
    example

    //Code==========
    L = ['Bin', 'Lisa', 'Bart', 'Paul'] #wanna get front 2 element?
    L2 = [L[0], L[1]] #NONONONONO
    print (L2)
    //Result==========
    ['Bin', 'Lisa']
    

    Using slicing format
    The first index is the index of first element you want to pick, and the second index is the next one of your last picked
    example

    //Code==========
    L = ['Bin', 'Lisa', 'Bart', 'Paul'] #wanna get front 2 element?
    L2 = L[0:2] # index of 0, 1, but stopped by 2 (won't be selected)
    print (L2)
    L3 = L[1:2] # index starting from 1, stopped by 2 (won't be selected)
    print (L3)
    L4 = L[:] # select all
    print (L4)
    L5 = L[::2] # from index 0, select one by skip one
    print (L5)
    //Result==========
    ['Bin', 'Lisa']
    ['Bin']
    ['Bin', 'Lisa', 'Bart', 'Paul']
    ['Bin', 'Bart']
    

    Using slicing format with reverse order
    negative index is also working well with slicing format
    example

    //Code==========
    L = ['Bin', 'Lisa', 'Bart', 'Paul'] #wanna get front 2 element?
    L2 = L[-2:] # index of -2 is `Bart`
    print (L2)
    L3 = L[0:-2] # index of -2 is `Bart`
    print (L3)
    L4 = L[-3:-1] # index of -3 is `Lisa`, index of -1 is 'Paul'
    print (L4)
    L5 = L[-4:-1:2] # index of -4 is `Bin`, index of -1 is 'Paul', 
    # actually selecting from ['Bin', 'Lisa', 'Bart'], each time select one and skip next one
    print (L5)
    //Result==========
    ['Bart', 'Paul']
    ['Bin', 'Lisa']
    ['Lisa', 'Bart']
    ['Bin', 'Bart']
    

    Slicing str

    SAME TO LIST :)

    相关文章

      网友评论

          本文标题:Slicing

          本文链接:https://www.haomeiwen.com/subject/xafsgftx.html