Python 初學者進階的九大技能
時間:2020-08-11 08:40:31
手機看文章
掃描二維碼
隨時隨地手機看文章
[導讀]對于初學者來說,Python是入門最簡單的語言之一。但學了一陣子之后,你可能會覺得:為如此簡單的操作寫大量的代碼有些令人困惑。
原文:https://medium.com/better-programming/9-skills-that-separate-a-beginner-from-an-intermediate-python-programmer-8bbde735c246
1.初學者與中級程序員
1.解決問題和提出問題:
2.XY問題:
“我需要從字符串中提取最后3個字符?!?
“不,你不需要。只需文件擴展名。”
def extract_ext(filename):return filename[-3:]print (extract_ext('photo_of_sasquatch.png'))>>> png
def extract_ext(filename):return filename.split('.')[-1]print (extract_ext('photo_of_sasquatch.png'))print (extract_ext('photo_of_lochness.jpeg'))>>> png>>> jpeg
os.path.splitext(),點擊這里查看:os.path.splitext():https://www.geeksforgeeks.org/python-os-path-splitext-method/。
3.理解代碼為何起作用(或不起作用):
4. 使用字符串:
word = 'supergreat'print (f'{word[0]}')>>> sprint (f'{word[0:5]}')>>> super
str()所提供的內容,但也可以不查看
str()文檔繼續(xù)編程。查看函數(shù)或過程文檔可以通過調用?
help(str)?或者
dir(str)來實現(xiàn)。執(zhí)行此操作時,你可能會發(fā)現(xiàn)一些并不知道的方法,也許你在查看
str()時,找到有個名叫?
endswith()?的方法,或許能用在某處。
endswith()?:
filenames = ['lochness.png' , 'e.t.jpeg' , 'conspiracy_theories_CONFIRMED.zip']# 1: Using ENDSWITHfor files in filenames:if files.endswith('zip'):print(f'{files} is a zip file')else:print (f'{files} is NOT a zip file')# 2: Using SPLITfor files in filenames:if files.split('.')[-1] == 'zip':print(f'{files} is a zip file (using split)')else:print (f'{files} is NOT a zip file (using split)')
5.使用列表:
my_list = ['a' , 'b' , 'n' , 'x' , 1 , 2 , 3, 'a' , 'n' , 'b']for item in my_list:print (f'current item: {item}, Type: {type(item)}')
print?(my_list.sort())
my_list = ['a' , 'b' , 'n' , 'x' , 1 , 2 , 3 , 'a' , 33.3 , 'n' , 'b']number_list = []string_list = []for item in my_list:print (f'current item: {item}, Type: {type(item)}')if not isinstance(item,str):number_list.append(item)else:string_list.append(item)my_list = string_list
my_list = [letter for letter in my_list if isinstance(letter,str)]
def get_numbers(input_char):if not isinstance(input_char,str):return Truereturn Falsemy_list = [1,2,3,'a','b','c']check_list = filter(get_numbers, my_list)for items in check_list:print(items)
names = ['First' , 'Middle' , 'Last']print(names[::-1])>>> ['Last', 'Middle', 'First']
names = ['First' , 'Middle' , 'Last']full_name = ' '.join(names)print(f'Full Name:\n{full_name}')>>> First Middle Last
6. 使用循環(huán):
greek_gods = ['Zeus' , 'Hera' , 'Poseidon' , 'Apollo' , 'Bob']for index in range(0,len(greek_gods)):print (f'at index {index} , we have : {greek_gods[index]}')
for name in greek_gods:print (f'Greek God: {name}')
for index, name in enumerate(greek_gods):print (f'at index {index} , we have : {name}')
7. 使用函數(shù)(并正確談論函數(shù)):
def print_list(input_list):for each in input_list:print(f'{each}')print() #just to separate outputgreek_gods = ['Zeus' , 'Hera' , 'Poseidon' , 'Apollo' , 'Bob']grocery_list = ['Apples' , 'Milk' , 'Bread']print_list(greek_gods)print_list(grocery_list)print_list(['a' , 'b' , 'c'])
def reverse_list(list_input):return list_input[::-1]my_list = ['a', 'b' , 'c']print (reverse_list(my_list))>>> ['c', 'b', 'a']
8.面向對象編程
class Student():def __init__(self,name):self._name = nameself._subject_list = []
student1 = Student('Martin Aaberge')
student2?=?Student('Ninja?Henderson')
student1和
student2都是student類的實例,它們共享同一個藍圖,但彼此之間并無關系。此時,我們對學生們能做的不多,但我們確實增加了一個主題列表。要填充此列表,我們需要創(chuàng)建方法,你可以調用方法來實現(xiàn)與該類實例的交互。
class Student():def __init__(self,name):self._name = nameself._subject_list = []def add_subject(self, subject_name):self._subject_list.append(subject_name)def get_student_data(self):print (f'Student: {self._name} is assigned to:')for subject in self._subject_list:print (f'{subject}')print()
#create students:student1 = Student('Martin Aaberge')student2 = Student('Heidi Hummelvold')#add subjects to student1student1.add_subject('psychology_101')student1.add_subject('it_security_101')#add subject to student2student2.add_subject('leadership_101')#print current data on studentsstudent1.get_student_data()student2.get_student_data()
student類,并將其導入我們的main.py文件(本案例中,它們都位于同一個文件夾中)。
from student import Studentstudent1 = Student('Martin')student1.add_subject('biomechanics_2020')student1.get_student_data()
snake_case,Python是以
snake_case來寫的,這代表著我們用下劃線來區(qū)分詞組,即便大學里也會犯錯,因此別難過,只要別這樣做就行了。這樣寫是對的:?
chocolate_cake?=?'yummy'
chocolateCake?=?'Yummy'
2、結論
推薦閱讀
免責聲明:本文內容由21ic獲得授權后發(fā)布,版權歸原作者所有,本平臺僅提供信息存儲服務。文章僅代表作者個人觀點,不代表本平臺立場,如有問題,請聯(lián)系我們,謝謝!






