Python 初学者进阶的九大技能
共 7660字,需浏览 16分钟
·
2020-08-01 03:18
初学者与中级程序员
解决问题和提出问题;
XY问题;
理解代码为何起作用(或不起作用);
使用字符串;
使用列表;
使用循环;
使用函数(并正确谈论函数);
面向对象编程;
尊重PEP。
1.解决问题和提出问题:
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
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}')
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']
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'
结论
往期精彩推荐 --
-- 留下你的 “在看” 呗!