Python (four)

1. Reverse the given string
// reverse each word, then reverse all characters, and finally synthesize a new word

def reverse(str_list,start,end):
    while start<end:
        str_list[start],str_list[end] = str_list[end],str_list[start]
        start += 1
        end -= 1

setence = ' Hello,how are you?    Fine.   '
str_list = list(setence)
i=0
while i <len(str_list):
    if str_list[i] != ' ':
        start = i
        end = start+1
        while (end<len(str_list)) and str_list[end]!= ' ':
            end += 1
        reverse(str_list,start,end-1)
        i=end
    else:
        i += 1
str_list.reverse()
print(str_list)

2. Slice
Slice less than end

li = list(range(10))
print(li[2:5])       //[3,,5]
print(li[:4]         //[0,1,2,3]
print(li[5:])        //[6,7,8,9]
print(li[0:10:3])    //[0,3,6,9]

Negative value handling

print(li[5:-2])    //[5,6,7]
print(li[9:0:-1])  //[9,8,7,6,5,4,3,2,1]
print(li[9::-1])   //[9,8,7,6,5,4,3,2,1,0]

Slice to generate a new object

print(li)

Quickly reverse an array

re_li = li[::-1]

Three, list comprehension
to generate a one-dimensional array

li = []
for i in range(10):
    li.append(i)

li = [1]*10

Generate the first 10 even numbers

li = [i*2 for i in range(10)]
print (li)

two-dimensional array assignment

错误做法
li_2d = [[0]*3] * 3
li_2d[0][0] = 100 //li_2d[0][0],[1][0],[2][0]都被修改为100,即为浅拷贝
正确做法
li_2d =  [[0]* for i in range(3)]

Quickly generate a list of ten numbers

d = {x:x%2==0 for x in range(10)}
//输出{0: True, 1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False}

Guess you like

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