Python基础(上)
【常见报错】¶
1、缩进不一致¶
- IndentationError: unindent does not match any outer indentation level
- IndentationError: unexpected indent
第一周知识点总结¶
#检查python版本
import sys
print(sys.version)
复制¶
#浅复制
message = 'Hello there'
new_message = message
print("new_message=", new_message)
print("message=", message)
message = 'Goodbye'
print("new_message=", new_message)
print("message=", message)
赋值¶
#建立一个值不赋值
var = None
print(var)
a=[111,11]
var=a
print(var)
#同时赋不同值
hello, goodbye = 'Hello', 'Goodbye'
print(hello)
print(goodbye)
变量名¶
- 区分大小写
- 不能以数字开头
- 起名要有意义
pass:暂时跳过,回头再写¶
类型转换¶
#检查object的类型是否正确---isinstance()
print(isinstance(1, int)) # True
print(isinstance(1, float)) # False
print(isinstance(3.14, float)) # True
print(isinstance(3.14, int)) # False
print(isinstance('Hello', str)) # True
print(isinstance('Hello', float)) # False
#类型转换
#int(), float(), str(), bool(), list(), tuple(), set(), dict()
# number will be a string:
number = input('Enter a number: ')
print(number, type(number))
# number will be an integer:
number = int(input('Enter a number: '))
print(number, type(number))
# number will be a float:
number = float(input('Enter a number: '))
print(number, type(number))
#类型转换失败
var = int('hello')
print(type(var))
#int()截断所有小数位
print(int(1.9))
print(int(-1.7))
使用常量Constant¶
- 用大写字母命名,下划线分隔单词
- 用处:用于解释特定数字,便于理解代码
- 通常情况下应定义一些普遍认知的数字为常量(例如:一天=24h)
- 常量可以被修改,但程序员有责任确保那些被认为是常量的变量在被定义后不会改变
#常量Constant举例
HOURS_PER_DAY = 24
MINUTES_PER_HOUR = 60
num_days = int(input('How many days? '))
num_minutes = num_days * HOURS_PER_DAY * MINUTES_PER_HOUR
print(num_days, 'days is', num_minutes, 'minutes')
# 幂power
print(10**2) # 10 to the power 2
print(2**3) # 2 to the power 3
# m div n
print(10//3) # 10 divided by 3 and rounded down
# 取余 %
print(10 % 3) # The remainder when 10 is divided by 3
#例
print(1+2*3) # Same as 1 + (2*3)
print(2**3*4) # Same as (2**3) * 4
print(24/6*2) # Same as (24/6) * 2
print(24/6/2) # Same as (24/6) / 2
print(2**2**3) # Same as 2**(2**3)
print(int('3') + float('2.0')) # Convert strings to numbers and add them
print(abs(-5)) # Absolute value of -5
print(pow(2, 4)) # 2 to the power of 4. This is the same as **
print(round(3.567, 2)) # Round 3.567 to 2 decimal places
-
x += 2 is equivalent to x = x + 2
-
x -= 2 is equivalent to x = x - 2
-
x = 2 is equivalent to x = x 2
-
x /= 2 is equivalent to x = x / 2
-
x //= 2 is equivalent to x = x // 2
-
x %= 2 is equivalent to x = x % 2
-
num1 == num2 is True if the value of num1 equals the value of num2, otherwise it is False
-
num1 is num2 is True if the value of num1 equals the value of num2, and num1 and num2 have the same type, otherwise it is False
-
num1 != num2 is True if the value of num1 does not equal the value of num2, otherwise it is False
-
num1 is not num2 is True if the value of num1 does not equal the value of num2, or num1 and num2 have different types, otherwise it is False
-
num1 < num2 is True if the value of num1 is less than the value of num2, otherwise it is False
-
num1 <= num2 is True if the value of num1 is less than or equal to the value of num2, otherwise it is False
-
num1 > num2 is True if the value of num1 is greater than the value of num2, otherwise it is False
-
num1 >= num2 is True if the value of num1 is greater than or equal to the value of num2, otherwise it is False
#例
print(1 == 1.0)
print(1 is 1.0)
浮点数自身计算问题¶
#浮点数可能存在的问题(因为其精度有限)
print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2)
#解决上述问题---round()
print(round(0.1111 + 0.222, 3))
print(round(0.3, 1))
print(round(0.1 + 0.2, 1) == round(0.3, 1))
#round:当遇到0.5时向偶数舍入
print(round(4.5,0))
print(round(5.5,0))
print(round(-4.5,0))
print(round(-5.5,0))
二、【字符串String】¶
# 空字符串与None的区别
empty = ''
none = None
print(empty)
print(none)
# 转义字符 \
# Backslash used to escape a quote mark
print('Penny\'s dog')
# Backslash used to escape a new line symbol
print('This is one line.\nThis is a second line')
# Backslash used to escape a tab symbol
print('Here\tThere')
# 回车 \n
# “”“保持内部格式输出”“”
# Using \n
text = 'This is one line.\nThis is a second line'
print(text)
# Using triple single quotes
text = '''This is one line.
This is a second line.'''
print(text)
# Using triple double quotes
text = """This is one line.
This is a second line.
This is a third line."""
print(text)
# 连接字符串 +
first_name = 'Leo'
last_name = 'Tolstoy'
full_name = first_name + ' ' + last_name
print(full_name)
# 字符串*数字
print('a' * 10)
1、字符串间比较¶
-
str1 == str2 is True if str1 and str2 are the same sequence of characters, otherwise it is False
-
str1 != str2 is True if str1 and str2 are not the same sequence of characters, otherwise it is False
-
str1 in str2 is True if str1 appears as a substring in str2, otherwise it is False
-
str1 not in str2 is True if str1 does not appear as a substring in str2, otherwise it is False
-
str1 < str2 is True if str1 is lexicographically less than (i.e. would appear earlier in the dictionary) the value of str2, otherwise it is False
-
Similarly we have str1 <= str2, str1 > str2, and str1 >= str2
2、以列表的方式读取str¶
y = 'abcdef'
print(y[0])
print(y[1:3])
print(y[1:-2])
# ==
print('A' == 'A')
# in
print('fish' in 'selfishness')
# 比大小
print('A' < 'B')
print('AA' < 'AB')
print('A' < 'AA')
3、切割字符串.split()¶
y = 'The\t cat\n sat on the mat'
print(y.split(' ')) #按空格切割
print(y.split()) #直接切割,去掉空格、回车、tab
z = '12:30:45'
print(z.split(':'))
4、String methods¶
-
str.capitalize() - Returns str with the first character uppercase and the rest lowercase
-
str.count() - Returns the number of times a specified value occurs in str
-
str.endswith() - Returns true if str ends with the specified value
-
str.find() - Searches str for a specified value and returns the index at which it is first found (or -1 if it was not found)
-
str.format() - Returns str formatted as specified
-
str.isalpha() - Returns true if all characters in str are from the alphabet
-
str.isdigit() - Returns true if all characters in str are digits
-
str.islower() - Returns true if all characters in str are lower case
-
str.isspace() - Returns true if all characters in strare whitespace characters (i.e. space, tab, or new line)
-
str.isupper() - Returns true if all characters in str are upper case
-
str.lower() - Returns str converted to lower case
-
str.lstrip() - Returns str with whitespace stripped from the left end
-
str.replace(old, new) - Returns str with old replaced by new
-
str.rfind() - Searches str for a specified value and returns the index at which it is last found (or -1 if it was not found)
-
str.rstrip() - Returns str with whitespace stripped from the right end
-
str.split() - Splits str using a specified delimiter and returns the result as a list
-
str.startswith() - Returns true if str starts with the specified value
-
str.strip() - Returns str with whitespace stripped from both ends
-
str.title() - Returns str with the first character of each word in upper case
-
str.upper() - Returns str with every character in upper case
# .startswith
print('A string'.startswith('A'))
print('A string'.startswith(' '))
# .isspace()
print(''.isspace())
print(' a'.isspace())
print(' '.isspace())
print(' '.isspace())
# \t is for tab
print(' \t\n'.isspace())
print('''
'''.isspace())
三、【布尔型 Booleans】¶
-
not x is True if x is False, otherwise it is False
-
x and y is True if x is True and y is True, otherwise it is False
-
x or y is True if x is True or y is True or both, otherwise it is False
guess = int(input('Enter a number: '))
print('Your number is between 2 and 5?')
print(guess>2 and guess<5)
print(not True)
print(not False)
print(not 3<5) # It is not the case that 3 is less than 5
# and
print(True and True)
print(True and False)
print(False and True)
print(False and False)
print((3<5) and (1+1==3)) # Are both these statements True?
# or
print(True or True)
print(True or False)
print(False or True)
print(False or False)
print((3<5) or (1+1==3)) # Is at least one of these statements True?
四、【IF语句】¶
number = int(input('What is your favourite number? '))
if number == 42:
print('That is my favourite number too!')
elif number == 21:
print('That is my second favourite number')
else:
print('That is neither of my favourite numbers.')
五、【While语句】¶
The while block can contain any statement(s) you like, including if statements and other while statements.
string = 'The quick brown fox jumped over the lazy dog'
print(len(string))
occurrences = 0
i = 0
while i < len(string):
if string[i] == 'e':
occurrences += 1
i += 1
print("The letter 'e' occurs", occurrences, "times")
continue跳到循环的下一迭代¶
i = 0
while i < 10:
i += 1
if i == 5:
continue
print(i)
print('Finished')
【解释】When the value of i gets to 5 the continue statement is executed, and Python jumps directly back to line 2 and continues. The number 5 does not get printed, but 6 - 10 do.
bresk 完全脱离循环¶
i = 0
while i < 10:
i += 1
if i == 5:
break
print(i)
print('Finished')
【解释】When the value of i gets to 5 the break statement is executed, and Python jumps directly to line 7. The number 5 does not get printed, and nor do 6 - 10.
保持程序持续运行¶
while True:
name = input('What is your name? (Enter x to stop) ')
if name == 'x':
break
print('Hello', name)
六、【files】读写文件¶
- 'r' - Open the file for reading. open will throw an exception (covered in Week 3) if the file does not exist
(如果文件不存在,open将抛出一个异常)¶
- 'w' - Open the file for writing. If the file exists, the contents are completely overwritten. If the file does not exist, it will be created.
(如果文件存在,内容将被完全覆盖。如果文件不存在,将创建它。)¶
- 'a' - Open the file for appending. The file is opened at the end and any writes to the file will append to the end. If the file does not exist it is created. This option is useful for adding information to a file - for example a log file.
(文件在末尾打开,对文件的任何写入都将附加到末尾。如果文件不存在,则创建该文件。该选项对于向文件(例如日志文件)添加信息非常有用。)¶
这些选项假定被访问的文件是文本文件。这也可以通过参数“rt”、“wt”和“at”变得更加明确。如果要访问的文件是二进制文件,则读取、写入和追加的参数分别为“rb”、“wb”和“ab”。¶
# Open a file for writing
with open('myfile', 'w') as f:
f.write('some text')
# f is automatically closed when control exits the with block
# Open the file again for reading
with open('myfile', 'r') as f:
# read returns all the data in the file
data = f.read()
print(data)
# Set up a file for reading
with open('myfile', 'w') as file:
file.write('Line 1: Some text\n') # Note: you have to include the newline character when writing to the file
file.write('Line 2: Some more text')
# Demonstrate the readline() method
with open('myfile', 'r') as file:
line_one = file.readline()
line_two = file.readline()
print(line_one)
print(line_two) # Just print the second line of the file
print(line_one.endswith('\n')) # The last character of line_one is the newline character
print(line_two.endswith('\n')) # line_two does not end in a newline character
read()和readline()方法是累积的——在文件关闭之前,read方法将跳过任何已经使用对read()或readline()的早期调用读取的内容。因此,例如,如果read()访问整个文件,任何后续的read()或readline()调用都将返回空字符串。
# Set up a file for reading
with open('myfile', 'w') as file:
file.write('Line 1: Some text\n')
file.write('Line 2: Some more text')
# Demonstrate using readline() and read() after a previous read() call
with open('myfile', 'r') as file:
content = file.read() # this reads the entire contents of the file, so
next_line = file.readline() # this call to readline() will not return any content
more_content = file.read() # and this call to read() will not return any content
print(next_line == "")
print(more_content == "")
(2)readlines()¶
# Set up the file for reading
with open('myfile', 'w') as file:
file.write('Line 1: Some content\n')
file.write('Line 2: ...\n')
file.write('Line 3: Last line')
with open('myfile', 'r') as file:
content = file.readlines()
print(content) # Note that the newline characters are included in the lines that had them
3、writelines()¶
列表中的每一行都应以换行符(' \n ')结尾,否则writelines()会将内容连接成一行。
lines = ['Line 1: The cat\n', 'Line 2: sat on\n', 'Line 3:', ' the mat']
with open('myfile', 'w') as file:
file.writelines(lines)
# Open the file to see the result
with open('myfile', 'r') as file:
content = file.readlines()
for line in content:
print(line) #每行之后有一个空行
print(line,end='') #用这种办法可以取消空行
4、for语句遍历¶
# Set up the file for reading
with open('myfile', 'w') as file:
line_one = 'Line 1: Some content\n'
line_two = 'Line 2: ...\n'
line_three = 'Line 3: Last line'
file.writelines([line_one, line_two, line_three])
# Demonstrate using the for command to loop through the lines of a file
with open('myfile', 'r') as file:
for line in file:
print(line)
print(line.endswith('\n')) #最后一行结尾没有\n
# 倒序取值
x = ['a', 'b', 'c', 'd', 'e']
print(len(x))
print(x[-1]) # x[len(x)-1]=x[5-1]=x[4]---即最后一个数
print(x[-2])
# 取一部分 [begin:end](左闭右开区间)
x = ['a', 'b', 'c', 'd', 'e']
print("x[1:3]=", x[1:3]) # x[1:3] = x[1] & x[2],左闭右开区间
print("x[1:-1]=", x[1:-1]) # x[1:-1] = x[1]~x[len(x)-1-1] = x[1]~x[4-1] = x[1],x[2],x[3]
print("x[:3]=", x[:3]) # x[0:3]= x[0],x[1],x[2]
print("x[1:]=", x[1:]) # x[1:]=x[1],x[2],x[3],x[4]
print("x[:]=", x[:])
# list[begin:end:step]
print(x[::2]) # Every second element
print(x[::3]) # Every third element
print(x[::-1]) # 反向
print(x[::-2]) # 反向&隔一个取一个
2、判断元素是否存在 + 查找元素出现的次数 + 查找元素位置¶
# 判断数字或字符是不是list中的元素 --- in
x = ['a', 'b', 'c1', 'd', 'e']
if 'c' in x:
print("'c' is in the list")
else:
print("'c' is not in the list")
#查找元素出现的次数 --- .count(元素内容)
x = [1, 3, 7, 8, 7, 5, 4, 6, 8, 5]
print(x.count(7))
y = ['a','a','a','e','d']
print(y.count('a'))
#查找满足要求的第一个元素的位置 --- .index(元素内容)
x = [1, 3, 7, 8, 7, 5, 4, 6, 8, 5]
print(x.index(7))
3、反向¶
# list反向 ---- .reverse()
x = ['dog', 'cat', 'mouse', 'horse', 'goat']
x.reverse()
print(x)
4、添加元素¶
# 在结尾添加 ----.append()
x = ['a', 'b', 'c', 'd', 'e']
x.append('f')
print(x)
# 自选位置添加 ----.insert(位置,添加的内容)
x = ['a', 'b', 'c', 'd', 'e']
x.insert(2, 'x')
print(x)
5、拼接两列表¶
# 拼接两个list ---- list1.extend(list2) 或直接 list1+list2
x = ['a', 'b', 'c', 'd', 'e']
y = ['x', 'y', 'z']
z=x+y
x.extend(y)
print(x)
print(z)
6、移除元素¶
# 移除元素 --- .pop() 或 del list[序号] 或 .remove(元素值)
# .pop()
x = ['a', 'b', 'c', 'd', 'e']
print(x.pop(2))
print("x=",x)
print(x.pop()) #不写删除的序号则删最后一个
print("x=",x)
# del list[序号]
y = ['a', 'b', 'c', 'd', 'e']
del y[1]
print("y=",y)
# .remove(元素值)
z = ['a', 'b', 'c', 'd', 'e', 'c']
z.remove('c') #从左向右删除满足要求的第一个值
print("z=",z)
7、清空列表 --- .clear()¶
x = ['a', 'b', 'c', 'd', 'e']
y=x
x.clear()
print('x=',x)
8、元素间计算¶
# 数字型加法
print(sum([1, 3, 7, 8, 7, 5, 4, 6, 8, 5]))
# 字符型加法(无,会报错)
print(sum(['q','q','w','e']))
9、布尔型返回值¶
# all()
#returns True if all items evaluate to True using the bool() function.
print(all([True, True, True]))
print(all(['a', 'a', 'a']))
print(all(['', 'a', 'b']))
# any()
#returns True if any items evaluate to True using the bool() function.
print(any([False, True, True]))
print(any(['a', 'a', 'a']))
print(any(['', 'a', 'b']))
print(any([False]))
10、排序.sort()¶
# 从小到大排序
x = [1, 5, 4, 2, 3]
x.sort()
print(x)
x = ['c', 'a', 'e', 'b', 'd']
x.sort()
print(x)
# 从大到小排序
x = [1, 5, 4, 2, 3]
x.sort(reverse=True)
print(x)
# 排序后赋值
x = [1, 5, 4, 2, 3]
y = sorted(x)
print(y)
y = sorted(x, reverse=True)
print(y)
# 按字母长度排序 (key=len)
x = ['dog', 'chicken', 'mouse', 'horse', 'goat', 'donkey']
x.sort(key=len)
print(x)
11、遍历列表loop¶
# 特别注意break和continue的应用
vowels = ['a', 'e', 'i', 'o', 'u']
print('Everything before o:')
for v in vowels:
if v == 'o':
break
print(v)
print('Everything except o:')
for v in vowels:
if v == 'o':
continue
print(v)
enumerate() 函数¶
#enumerate() 将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列
#同时列出数据和数据下标
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
print(list(enumerate(seasons, start=1))) # 下标从 1 开始
# 多用于循环
vowels = ['a', 'e', 'i', 'o', 'u']
for i, v in enumerate(vowels):
print('The vowel at index', i, 'is', v)
range(起点,终点,步长)¶
包含范围是:[起点,终点)
for i in range(10):
print(i)
for i in range(3, 10):
print(i)
for i in range(1, 11):
for j in range(1, 11):
print(i, 'times', j, 'is', i*j)
for i in range(2):
for j in range(2):
for k in range(2):
print(i, j, k)
12、二维数组¶
# reverse()单独写不针对嵌套的数组,应定位至该数组再reverse(),如下一代码
numbers = [[1,2,3],[3,4,5],[6,7,8]]
print(len(numbers))
print(numbers[0])
numbers.reverse()
print(numbers)
# 获取内部嵌套数组的单个值 & 排序
numbers = [[1,2,3],[3,4,5],[5,6,7]]
print(len(numbers[0]))
print(numbers[0][0])
numbers[0].reverse()
print(numbers[0])
# 所有数字相加
numbers = [[1,2,3],[3,4,5],[5,6,7]]
total = 0
for i in numbers:
print(i)
for j in i:
total += j
print(j)
print(total)
八、Tuples 元组¶
- 不可更改
- 其他操作与list相同
x = ('a', 'b', 'c', 'd', 'e')
y = (1, 1, 2, 3)
# 长度
print(len(x))
print(len(y))
# 查找元素
print(4 in y)
print(y.count(1))
# 取值
print(x[2])
print(x[-1])
print(x[1:3])
#合并两元祖
z = x + y # Note this will give a tuple
print(z)
#元素值之和
print(sum(y))
#判断元素类型
t = (True, False, True)
print(any(t))
print(all(t))
#如果赋值的时候什么都不加,直接默认为tuple
y=1,2,3
print(y)
# 特别注意!!!!! (单个值)不是tuple
y=10
z=(10)
print(y)
print(z)
九、集合¶
- 元素的唯一性(同一对象只可包含一个)
- 无序的,没有索引(例:a[0])
#无序的
vowels = {'b', 'e', 'i', 'o', 'u'}
print(vowels)
#忽略相同对象,只保留第一个
x = {'cat', 'mouse', 'dog', 'cat', 'cat'}
print(x)
# 添加元素
vowels = set()
vowels.add('a')
vowels.add('e')
vowels.add('e') # No error, just not added
print(vowels)
vowels.update('b', 'c')
print(vowels)
# 删除元素
vowels = {'a', 'e', 'i', 'o', 'u'}
vowels.remove('a')
print(vowels)
# 用.discard()删除没有的元素不会报错,用.remove()删除没有的元素会报错
vowels.discard('f') # No error
print(vowels)
vowels.remove('f') # Error
# 清空集合
vowels = {'a', 'e', 'i', 'o', 'u'}
vowels.clear()
print(vowels)
#获取长度
print(len({'a', 'e', 'i', 'o', 'u'}))
print(len({}))
#查找元素
names = {'John', 'Bob', 'Alice'}
print('John' in names)
print('Eve' in names)
# 迭代
x = {'cat', 'mouse', 'dog', 'cat', 'cat'}
print(x)
for vowel in x:
print(vowel.upper())
for zzz in {'a', 'e', 'i', 'o', 'u'}:
print(zzz.upper())
并集与交集¶
#并集
evens = {2, 4, 6, 8}
primes = {2, 3, 5, 7}
#下面三种方式均可
print(evens | primes)
print(evens.union(primes))
print(primes.union(evens))
#交集
evens = {2, 4, 6, 8}
primes = {2, 3, 5, 7}
print(evens & primes)
print(evens.intersection(primes))
print(primes.intersection(evens))
#两集合之间的差异
evens = {2, 4, 6, 8}
primes = {2, 3, 5, 7}
print(evens - primes)
print(evens.difference(primes))
print(primes - evens)
print(primes.difference(evens))
十、字典¶
- 无序集合
#定义字典
scores = {
'Alice': 'a',
'Bob': '1',
'Eve': 'three',
'Mallory': 3,
}
print(scores)
print(scores['Alice'])
#字典的key和value不用是同一类型
dictionary = {
1: 'one',
'two': 2, # Mixing key types is not good practice as it can lead to confusion
3: 3
}
print(dictionary)
# An empty dictionary
{}
# A dictionary with 4 keys, mapping names of digits to digits.
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
# A dictionary with 4 keys, mapping English words to German translations
{'tap': 'Hahn', 'table': 'Tisch', 'rooster': 'Hahn', 'train': 'Zug'}
# A dictionary with 3 keys, mapping German words to English translations
{'Hahn': ['tap', 'rooster'], 'Tisch': ['table'], 'Zug': ['train']}
#key必须是唯一的,多了会被忽略
scores = {
'Alice': 1,
'Bob': 1
}
print(scores)
scores = {
'Alice': 1,
'Alice': 1
}
print(scores)
#更新键值
scores = {
'Alice': 0,
'Bob': 1,
'Eve': 2,
'Mallory': 3,
}
scores['Bob'] = 900
scores['Alice'] += 1
print(scores)
# 删除key,即删除该组
scores = {
'Alice': 0,
'Bob': 1,
'Eve': 2,
'Mallory': 3,
}
del scores['Bob']
print(scores)
# 只输出key值
scores = {
'Alice': 0,
'Bob': 1,
'Eve': 2,
'Mallory': 3,
}
for key in scores:
print(key)
# 获取所有值,一一对应
a=[]
b=[]
scores = {
'Alice': 0,
'Bob': 1,
'Eve': 2,
'Mallory': 3,
}
for key, value in scores.items():
print(key, value)
#scores.items(key,value)
#scores(key)
十一、各类型间转换¶
- list()
- tuple()
- set()
- dict()
x = [1, 1, 1, 2, 3, 4, 5]
print(tuple(x))
print(set(x))
x = { 1, 2, 3 }
print(list(x))
print(tuple(x))
x = (1, 2, 3)
print(list(x))
print(set(x))
# 字典与列表的转换
#(1)字典-->列表
scores = {
'Alice': 0,
'Bob': 1,
'Eve': 2,
'Mallory': 3,
}
# Using the list() function will yield only keys
print(list(scores))
# Using the list() function on .items will yield the tuples
print(list(scores.items()))
#(2)列表-->字典
scores = [(1, 'A'), (2, 'B')]
scores_dict = dict(scores)
print(scores_dict)
print(type(scores))
print(type(scores_dict))
[a1, b1, c1] = [10, 11, 12]
# Simplified syntax for what could also be written as
# (a2, b2, c2) = (21, 22, 23)
# or
# a2, b2, c2 = (21, 22, 23)
# or
# (a2, b2, c2) = 21, 22, 23
a2, b2, c2 = 21, 22, 23
# Simplified syntax for what could also be written as
# [a3, b3, c3] = (31, 32, 33)
[a3, b3, c3] = 31, 32, 33
# Simplified syntax for what could also be written as
# (a4, b4, c4) = [41, 42, 43]
a4, b4, c4 = [41, 42, 43]
print([a1, b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4])
# Simplified syntax for what could also be written as
# (a1, b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4)
a1, b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4
# Singleton dictionary and set, respectively
print(type({'one': 1}))
print(type({'one'}))
# Empty dictionary and set, respectively
print(type({})) #dictionary
print(type(set())) #set

浙公网安备 33010602011771号