Python (nine) slice

Although I don't know what the hell is, but I feel quite powerful, so I started to learn.
The slice operation is used to take the first N elements of the list. Of course, we can use loops to achieve this operation

def qu(l,num):
    x=0
    L2=[]
    while x<num:    
         L2.insert(x,L[x]) 
         x=x+1
    return L2     
L3=qu(['a','b','c','d'], 2)
#取出前两个数
print(L3)

OR

 r = []
 n = 3
 for i in range(n):
     r.append(L[i])

The Slice operator can greatly simplify this operation
PS: ( ^__^ ) Hee hee, nbnb.

L[0:3]
['Adam', 'Lisa', 'Bart']
#如果是从0开始取,0可以省略 也就是L[:3],L[:]表示从头到尾
L[::2]
['Adam', 'Bart']

The third parameter means to take one every N, and the above L[::2] will take one out of every two elements, that is, take one every other.
Replacing the list with a tuple, the slicing operation is exactly the same, but the result of the slicing also becomes a tuple.

The task
range() function can create an array of numbers:

>>> range(1, 101)
[1, 2, 3, ..., 100]

Please use slices and take out:
1. The first 10 numbers;
2. Multiples of 3;
3. Multiples of 5 not greater than 50.

L = range(1, 101)
print( L[1:11])
print( L[2:3])
print( L[4:50:5])
输出:
range(1, 11)
range(3, 4)
range(5, 51, 5)
#不知道是什么鬼····

I checked, python3 canceled the range, and renamed xrange to range. If you want to print out the entire structure like py2, you need list(range(...))

L = range(1, 101)
print( list(L[:10]))
print( list(L[2::3]))
print( list(L[4:50:5]))
输出
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

Slicing in reverse order

>>> L = ['Adam', 'Lisa', 'Bart', 'Paul']

>>> L[-2:]
['Bart', 'Paul']

>>> L[:-2]
['Adam', 'Lisa']

>>> L[-3:-1]
['Lisa', 'Bart']

>>> L[-4:-1:2]
['Adam', 'Bart']

Reverse-order slices contain the start index, but not the end index.

Task
Use reverse slicing to extract from the sequence of 1 - 100:
* the last 10 numbers;
* the last 10 multiples of 5.

L = range(1, 101)
print L[-10:]
print L[-46::5]

string slice

>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[-3:]
'EFG'
>>> 'ABCDEFG'[::2]
'ACEG'

Task
Strings have a method upper() that converts characters to uppercase:

 'abc'.upper()
 >>>'ABC'

But it will make all letters uppercase. Please design a function that takes a string and returns a string with only the first letter capitalized. Use [1:] reference code
to take the string except the first letter :

def firstCharUpper(s):
    return s[0].upper() + s[1:]
print firstCharUpper('hello')
print firstCharUpper('sunday')
print firstCharUpper('september')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325733122&siteId=291194637