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]}')
>>> s
print (f'{word[0:5]}')
>>> super
str()
所提供的内容,但也可以不查看
str()
文档继续编程。查看函数或过程文档可以通过调用
help(str)
或者
dir(str)
来实现。执行此操作时,你可能会发现一些并不知道的方法,也许你在查看
str()
时,找到有个名叫
endswith()
的方法,或许能用在某处。
endswith()
:
filenames = ['lochness.png' , 'e.t.jpeg' , 'conspiracy_theories_CONFIRMED.zip']
# 1: Using ENDSWITH
for 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 SPLIT
for 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 True
return False
my_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. 使用循环:
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. 使用函数(并正确谈论函数):
def print_list(input_list):
for each in input_list:
print(f'{each}')
print() #just to separate output
greek_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 = name
self._subject_list = []
student1 = Student('Martin Aaberge')
student2 = Student('Ninja Henderson')
student1
和
student2
都是student类的实例,它们共享同一个蓝图,但彼此之间并无关系。此时,我们对学生们能做的不多,但我们确实增加了一个主题列表。要填充此列表,我们需要创建方法,你可以调用方法来实现与该类实例的交互。
class Student():
def __init__(self,name):
self._name = name
self._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 student1
student1.add_subject('psychology_101')
student1.add_subject('it_security_101')
#add subject to student2
student2.add_subject('leadership_101')
#print current data on students
student1.get_student_data()
student2.get_student_data()
student
类,并将其导入我们的main.py文件(本案例中,它们都位于同一个文件夹中)。
from student import Student
student1 = Student('Martin')
student1.add_subject('biomechanics_2020')
student1.get_student_data()
snake_case
,Python是以
snake_case
来写的,这代表着我们用下划线来区分词组,即便大学里也会犯错,因此别难过,只要别这样做就行了。这样写是对的:
chocolate_cake = 'yummy'
chocolateCake = 'Yummy'
2、结论
推荐阅读
免责声明:本文内容由21ic获得授权后发布,版权归原作者所有,本平台仅提供信息存储服务。文章仅代表作者个人观点,不代表本平台立场,如有问题,请联系我们,谢谢!