Python大佬 | 菜鸟进阶必备的九大技能!
机器学习算法与Python实战
共 7330字,需浏览 15分钟
·
2020-11-27 19:17
↑↑↑点击上方蓝字,回复资料,10个G的惊喜
解决问题和提出问题; XY问题; 理解代码为何起作用(或不起作用); 使用字符串; 使用列表; 使用循环; 使用函数(并正确谈论函数); 面向对象编程; 尊重PEP。
如果想要了解更多关于编程提问的技能,我另有一篇文章,链接如下(英文):How to Ask Questions About Programming:https://medium.com/better-programming/how-to-ask-questions-about-programming-dcd948fcd2bd
“我需要从字符串中提取最后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
使用字符串
word = 'supergreat'
print (f'{word[0]}')
>>> s
print (f'{word[0:5]}')
>>> super
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)}')
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
即便有些混乱,这也是一种有效的方式,可以运行,不过经过重构可以用单行来表示! 如果想要生活多些乐趣,请学习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}')
使用函数(并正确谈论函数)
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']
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()
chocolate_cake = 'yummy'
chocolateCake = 'Yummy
评论