Python大佬 | 菜鸟进阶必备的九大技能!
![](https://filescdn.proginn.com/fdcf04ce9b47415cc311c03eada353c6/79b33730466dc02b420f3fa81a1f46a0.webp)
初学者与中级程序员
初学者与中级程序员
解决问题和提出问题; XY问题; 理解代码为何起作用(或不起作用); 使用字符串; 使用列表; 使用循环; 使用函数(并正确谈论函数); 面向对象编程; 尊重PEP。
解决问题和提出问题
解决问题和提出问题
How to Ask Questions About Programming:https://medium.com/better-programming/how-to-ask-questions-about-programming-dcd948fcd2bd
XY问题
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
https://www.geeksforgeeks.org/python-os-path-splitext-method/
理解代码为何起作用(或不起作用)
理解代码为何起作用(或不起作用)
![](https://filescdn.proginn.com/e2b7114c106c854606a50284599487c4/0e8bb923e031b9e6e2d7354911ad0e2c.webp)
右侧是折叠了if/else语句的ATOM
![](https://filescdn.proginn.com/dec5b027057e0aabb2b305f519349963/e10fbf71e40e3f7ab01f7d50af176bb2.webp)
使用字符串
使用字符串
word = 'supergreat'
print (f'{word[0]}')
>>> s
print (f'{word[0:5]}')
>>> super
![](https://filescdn.proginn.com/9fc12dea338072d046636259b4e5f0f7/b4f630431fc1e6b73ef03e4effb995b8.webp)
![](https://filescdn.proginn.com/30976df4e6cf141cb78da87a5debd4aa/c43906803ef384db0ddf907b61118426.webp)
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)')
使用列表
使用列表
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)}')
![](https://filescdn.proginn.com/467188aed9bf772afd0334f6d50c978f/408b9c8e059428ae1c30b4c950fbea79.webp)
print (my_list.sort())
![](https://filescdn.proginn.com/9d1e211badc86b4c6b53c5fa3008fd31/7d5d61ea3397f2e3fd91a79a3273fa1b.webp)
如果我们想把整数与字母分开要怎么做?一种方式是通过循环来实现,我们可以遍历列表中的所有项目。初学者很早就会使用循环了,循环对于编程也很重要。 代码可能是下面这样的: 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
即便有些混乱,这也是一种有效的方式,可以运行,不过经过重构可以用单行来表示! 如果想要生活多些乐趣,请学习Python的列表解析式下面是同样问题通过列表解析式得出的: 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 Last6. 使用循环:
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}')
![](https://filescdn.proginn.com/a9df2ce9e75d3454f8efce031ea4d497/977de46129e1e824a15a1a5d9af65b55.webp)
使用函数(并正确谈论函数)
使用函数(并正确谈论函数)
![](https://filescdn.proginn.com/569cc7e37920451b420ee555068f94c2/140ead78a3647eee34942934426e64d6.webp)
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'])
![](https://filescdn.proginn.com/8b313c8319cc10b70f0af1b7b641989a/80bbe3f8d205a304053833dec7138770.webp)
def reverse_list(list_input):
return list_input[::-1]
my_list = ['a', 'b' , 'c']
print (reverse_list(my_list))
>>> ['c', 'b', 'a']
面向对象编程
面向对象编程
class Student():
def __init__(self,name):
self._name = name
self._subject_list = []
如果想要创建一个student,可以像这样将其分配给变量:student1 = Student('Martin Aaberge')如果需要更多student,可以使用同一个类并添加另外的姓名:
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()
from student import Student
student1 = Student('Martin')
student1.add_subject('biomechanics_2020')
student1.get_student_data()
![](https://filescdn.proginn.com/a8b21dfdf7bf955415c6437ae38c240a/ec4c45a0c20a196d00e91c4ea8258abd.webp)
![](https://filescdn.proginn.com/0a72392ff49e307be64ec7219e9cdc0c/f24e85f06e2db7861d29c4839464dc4c.webp)
尊重PEP
chocolate_cake = 'yummy'
chocolateCake = 'Yummy
https://medium.com/better-programming/9-skills-that-separate-a-beginner-from-an-intermediate-python-programmer-8bbde735c246
实习/全职编辑记者招聘ing
加入我们,亲身体验一家专业科技媒体采写的每个细节,在最有前景的行业,和一群遍布全球最优秀的人一起成长。坐标北京·清华东门,在大数据文摘主页对话页回复“招聘”了解详情。简历请直接发送至zz@bigdatadigest.cn
![](https://filescdn.proginn.com/3879be094430b0ccf6ba070b8e70dfcd/7d9745b515f1344d895382e6d35f9de0.webp)
评论