Recent Python video tutorials on YouTube to learn the basics of Python, video by Corey Schafer production, speak very simple and clear, the English pronunciation is clearer, almost all can understand, is a good python introductory learning video, but also can learn English. This blog in the code to record the relevant basic knowledge, although very simple, but you write again to deepen the impression.
Slicing Lists and Strings (sliced)
The slices are used to manipulate the list and string types, and the following are some examples of slicing.
# syntax List[start:end:step]My_list=[0,1,2,3,4,5,6,7,8,9]# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9# -10,-9,-8,-7,-6,-5,-4,-3,-2,-1Printmy_list[1:5]# Result: [1, 2, 3, 4]Printmy_list[-7:-2]# Result: [3, 4, 5, 6, 7]Printmy_list[:]# Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]#间隔为2Printmy_list[1:8:2]# Result: [1, 3, 5, 7]#反转listPrintmy_list[::-1]# Result: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]#String同样可以用切片Sample= "Hello World"Printsample[::-1]# Result:dlrow Olleh
Comprehensions (generated)
A build can generate multiple lists in a very concise language.
Nums=[1,2,3,4,5,6,7,8,9,Ten]my_list=[]#---I want ' n*n ' for each ' n ' in Nums# Traditional Way# for N in Nums:# my_list.append (n)# built- inMy_list=[n*N forNinchNumsPrintMy_list# Result: [1, 4, 9, +, +,----#---I want ' n ' for each ' n ' in Nums if ' n ' is even# Traditional Way#for N in nums:# if n%2 = = 0:# my_list.append (n)# built- inMy_list=[n forNinchNumsifN%2==0]PrintMy_list# Result: [2, 4, 6, 8, ten]#---I want a (letter, num) pair for each of the "ABC" and each num in "012"#传统方式#for letter in ' abc ':# for NUM in range (3)# My_list.append ((letter,num))# built- inMy_list=[(Letter, NUM) forLetterinch ' abc ' forNuminch Range(3)]PrintMy_list# Result: [(' A ', 0), (' A ', 1), (' A ', 2), (' B ', 0), (' B ', 1), (' B ', 2), (' C ', 0), (' C ', 1), (' C ', 2)]# Dictionary ComprehensionsNames=[' Bruce ',' Clark ',' Peter ']heros=[' Batman ',' Superman ',' Spiderman ']# I want a dict{' name ': ' Hero '} for each name, hero in Zip (name, heros)# Traditional WayMy_dict={}#for name, hero in Zip (names, heros):# My_dict[name] = Hero# generated note for curly bracesMy_dict={Name:hero forName, Heroinch Zip(Names, Heros)}PrintMy_dict# Result: {' Bruce ': ' Batman ', ' Peter ': ' Spiderman ', ' Clark ': ' Superman '}# Set ComprehensionsNums=[1,1,2,3,3,4,5]# generated note for curly bracesMy_set={N forNinchNumsPrintMy_set# result set ([1, 2, 3, 4, 5])
Python Basics--slice (slices) and comprehensions (generated)