Python语法速查表

编程入门 行业动态 更新时间:2024-10-15 08:18:44

Python<a href=https://www.elefans.com/category/jswz/34/1770552.html style=语法速查表"/>

Python语法速查表

由于学的语言很杂乱又不精深,混乱的脑袋常常搞不清楚,所以做一个速查表类似的东西,持续更新中…

Printing
# Hello
print('Hello')# Hello world
print('Hello' + ' ' + 'world')# Hello world
print('Hello', 'world')# Hello world
print('Hello' + ' ' + 'world')# Hello    world
print('Hello' + '\t' + 'world')# Hello
# world
print('Hello' + '\n' + 'world')
Working with text
# 5
print(len('Hello'))# 8
print(len('  Hello '))# 5
#(移除字符串头尾指定的字符)(完整形式为.strip([char]))
print(len('  Hello '.strip()))# Hello.
print('Hello.'.strip())# Hello
print('Hello.'.strip('.'))# ['Hello.', 'My', 'name', 'is', 'Ben.', 'I', 'am', '185cm', 'tall.']
# ['Hello', ' My name is Ben', ' I am 185cm tall', '']
#(根据指定的字符分割字符串,返回list)(完整形式为.split([char]))
passage = "Hello. My name is Ben. I am 185cm tall."
words = passage.split(' ')
sentences = passage.split('.')
print(words)
print(sentences)
Working with lists
# [1, 2, 3, 4, 5]
# (创建一个列表)
numbers = [1, 2, 3, 4, 5]
print(numbers)# 5
numbers = [1, 2, 3, 4, 5]
print(len(numbers))# 1
# 5
numbers = [1, 2, 3, 4, 5]
# Print the first item:
print(numbers[0])
# Print the last item:
print(numbers[-1])# 2
# 4
# 6
# 8
# 10
numbers = [1, 2, 3, 4, 5]
for n in numbers:print(2 * n)# ['cat', 'dog', 'goat', 'mouse', 'python']
# (不返回新的列表,完整表达为.sort(key=None, reverse=False),key为指定元素,reverse = True 降序)
words = ['dog', 'cat', 'mouse', 'goat', 'python']
words.sort()
print(words)# hello
# h-e-l-l-o
# h[ ]e[ ]l[ ]l[ ]o
letters = ['h', 'e', 'l', 'l', 'o']
print(''.join(letters))
print('-'.join(letters))
print('[ ]'.join(letters))
Working with dictionaries
# 17
# 3
pet_frequencies = {'dog': 17, 'cat': 12}
print(pet_frequencies['dog'])
pet_frequencies['mouse'] = 3
print(pet_frequencies['mouse'])# None
# 0
# No such pet
# (如果直接访问不存在的key会得到error,我们使用.get()来避免该状况的发生,默认返回None)
pet_frequencies = {'dog': 17, 'cat': 12, 'mouse': 3}
print(pet_frequencies.get('hare'))
print(pet_frequencies.get('hare', 0))
print(pet_frequencies.get('hare', 'No such pet'))# dict_keys(['dog', 'cat', 'mouse'])
pet_frequencies = {'dog': 17, 'cat': 12, 'mouse': 3}
print(pet_frequencies.keys())# dog 17
# cat 12
# mouse 3
pet_frequencies = {'dog': 17, 'cat': 12, 'mouse': 3}
for key in pet_frequencies:print(key, pet_frequencies[key])# dog 17
# cat 12
# mouse 3
pet_frequencies = {'dog': 17, 'cat': 12, 'mouse': 3}
for key, value in pet_frequencies.items():print(key, value)
Type conversions
# ERROR
# (反面教材,str不能直接加num,需要type conversion)
word = 'Hello'
number = 2
print(word + number)# ERROR
# (反面教材,str不能直接除以num,需要type conversion)
word = 'Hello'
number = 2
print(word/number)# Hello2
word = 'Hello'
number = 2
print(word + str(number))
Built-in functions
# 5
# 5
# max() takes two or more arguments and returns the maximum value
print(max(3, 5, 0, 4))
# max() can also take a list as argument
print(max([3, 5, 0, 4]))# 12
# sum() takes a list as argument and returns the sum of its elements
print(sum([3, 5, 0, 4]))
Lambda functions
# 7
# You can have anonymous functions or function literals by lambda
add = lambda x, y: x + y
print(add(3, 4))# d
# c
# m
# g
# p
# (.map()会根据提供的函数对指定序列做映射,完整形式为.map(function, iterable, ...))
words = ['dog', 'cat', 'mouse', 'goat', 'python']
first_letters = map(lambda word: word[0], words)
for letter in first_letters:print(letter)# d
# c
# m
# g
# p
def get_first_letter(word):return word[0]
words = ['dog', 'cat', 'mouse', 'goat', 'python']
first_letters = map(get_first_letter, words)
for letter in first_letters:print(letter)
Yielding values
# 1
# 2
# 3
# 4
# 5
def numbers():return [1,2,3,4,5]
for x in numbers():print(x)# 1
# 2
# 3
# 4
# 5
# (the diff here is 'yield' does not waiting for the whole results come out,
# it may waiting for a block of results calculated and yield it out immediately,
# then continuing to do the calculation so that it saves more memory.)
# (In this case numbers does not return a list - it returns a generator.
# When you iterate through this generator in line 4 (which contains numbers())
# it generates the numbers one-by-one as they are needed.  )
def numbers():for x in [1,2,3,4,5]:yield x
for x in numbers():print(x)
Defining classes
# Jacinda Ardern
# Ardern, Jacinda
# Ardern, J.
class Person:def __init__(self, firstName, lastName):self.firstName = firstNameself.lastName = lastNamedef fullName(self):return self.firstName + ' ' + self.lastNamedef reverseName(self, initialOnly = False):if initialOnly:return self.lastName + ', ' + self.firstName[0] + '.'else:return self.lastName + ', ' + self.firstName
person = Person('Jacinda', 'Ardern')
print(person.fullName())
print(person.reverseName())
print(person.reverseName(True))# Jacinda Ardern
# Master Stuart Simpson
# (说到class就是老生常谈的继承,封装,多态,牢记,牢记)
class Person:def __init__(self, firstName, lastName):self.firstName = firstNameself.lastName = lastNamedef fullName(self):return self.firstName + ' ' + self.lastName
class Boy(Person):def fullName(self):return 'Master ' + self.firstName + ' ' + self.lastName
person = Person('Jacinda', 'Ardern')
print(person.fullName())
boy = Boy('Stuart', 'Simpson')
print(boy.fullName())
Importing code
# (importing math libraries)
import math# 2
# (use math lib)
import math
print(math.floor(2.76))# 2
# (instead of importing the whole lib, you can use only some functions from that)
from math import floor
print(floor(2.76))# 18
# (use __name__ to check if the program running as the main program)
def triple(x):return x * 3
if __name__ == '__main__':print(triple(6))
Using standard input
# (this will output your input, try it on your machine)
import sys
for line in sys.stdin:line = line.strip()if line == 'exit':breakelse:print('You entered ' + line)
print('Done')

更多推荐

Python语法速查表

本文发布于:2024-03-10 09:35:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1727607.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   速查表   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!