Python基础(上)

 

【常见报错】

 

1、缩进不一致

  • IndentationError: unindent does not match any outer indentation level
  • IndentationError: unexpected indent
 

第一周知识点总结

In [1]:
#检查python版本

import sys
print(sys.version)
 
3.7.9 (default, Aug 31 2020, 07:22:35) 
[Clang 10.0.0 ]
 

复制

In [4]:
#浅复制

message = 'Hello there'
new_message = message

print("new_message=", new_message)
print("message=", message)

message = 'Goodbye'
print("new_message=", new_message)
print("message=", message)
 
new_message= Hello there
message= Hello there
new_message= Hello there
message= Goodbye
 

赋值

In [2]:
#建立一个值不赋值

var = None
print(var)

a=[111,11]
var=a

print(var)
 
None
[111, 11]
In [3]:
#同时赋不同值

hello, goodbye = 'Hello', 'Goodbye'
print(hello)
print(goodbye)
 
Hello
Goodbye
 

变量名

  • 区分大小写
  • 不能以数字开头
  • 起名要有意义
 

pass:暂时跳过,回头再写

 

类型转换

In [3]:
#检查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
 
True
False
True
False
True
False
In [5]:
#类型转换

#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))
 
Enter a number: 1
1 <class 'str'>
Enter a number: s
 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-43b7d70a6506> in <module>
      8 
      9 # number will be an integer:
---> 10number = int(input('Enter a number: '))
     11 print(number, type(number))
     12 

ValueError: invalid literal for int() with base 10: 's'
In [9]:
#类型转换失败

var = int('hello')
print(type(var))
 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-6284a67860b8> in <module>
      1 #类型转换失败
      2 
----> 3var = int('hello')
      4 print(type(var))

ValueError: invalid literal for int() with base 10: 'hello'
In [7]:
#int()截断所有小数位

print(int(1.9))
print(int(-1.7))
 
1
-1
 

使用常量Constant

  • 用大写字母命名,下划线分隔单词
  • 用处:用于解释特定数字,便于理解代码
  • 通常情况下应定义一些普遍认知的数字为常量(例如:一天=24h)
  • 常量可以被修改,但程序员有责任确保那些被认为是常量的变量在被定义后不会改变
In [8]:
#常量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')
 
How many days? 12
12 days is 17280 minutes
 

一、【数字】

数字计算

In [1]:
# 幂power

print(10**2) # 10 to the power 2
print(2**3)  # 2 to the power 3
 
100
8
In [2]:
# m div n 

print(10//3) # 10 divided by 3 and rounded down
 
3
In [3]:
# 取余 %

print(10 % 3) # The remainder when 10 is divided by 3
 
1
 

计算优先级

  • **优先级最高
  • *、/、//、%其次
  • +、-最后

int(), float(), abs(), pow(), round()

In [12]:
#例

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
 
7
32
8.0
2.0
256
5.0
5
16
3.57
 
  • 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

 

数字间比较

==和is的区别

 
  • 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

In [13]:
#例
print(1 == 1.0)
print(1 is 1.0)
 
True
False
 

浮点数自身计算问题

In [14]:
#浮点数可能存在的问题(因为其精度有限)

print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2)
 
0.30000000000000004
In [17]:
#解决上述问题---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))
 
0.333
0.3
True
4.0
6.0
-4.0
-6.0
 

二、【字符串String】

In [14]:
# 空字符串与None的区别
empty = ''
none = None
print(empty)
print(none)
 
None
In [20]:
# 转义字符 \

# 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')
 
Penny's dog
This is one line.
This is a second line
Here	There
In [19]:
# 回车 \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)
 
This is one line.
This is a second line
This is one line.
This is a second line.
This is one line.
This is a second line.
This is a third line.
In [20]:
# 连接字符串 +

first_name = 'Leo'
last_name = 'Tolstoy'
full_name = first_name + ' ' + last_name
print(full_name)
 
Leo Tolstoy
In [21]:
# 字符串*数字

print('a' * 10)
 
aaaaaaaaaa
 

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

In [71]:
y = 'abcdef'
print(y[0])
print(y[1:3])
print(y[1:-2])
 
a
bc
bcd
In [22]:
# ==
print('A' == 'A')

# in
print('fish' in 'selfishness')

# 比大小
print('A' < 'B')
print('AA' < 'AB')
print('A' < 'AA')
 
True
True
True
True
True
 

3、切割字符串.split()

In [14]:
y = 'The\t cat\n sat on the mat'
print(y.split(' '))  #按空格切割
print(y.split())   #直接切割,去掉空格、回车、tab

z = '12:30:45'
print(z.split(':'))
 
['The\t', 'cat\n', 'sat', 'on', 'the', 'mat']
['The', 'cat', 'sat', 'on', 'the', 'mat']
['12', '30', '45']
 

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

In [7]:
# .startswith

print('A string'.startswith('A'))
print('A string'.startswith(' '))
 
True
False
In [17]:
# .isspace()

print(''.isspace())
print(' a'.isspace())
print(' '.isspace())
print('   '.isspace())

# \t is for tab
print('   \t\n'.isspace())
print('''



'''.isspace())
 
False
False
True
True
True
True
 

三、【布尔型 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

In [32]:
guess = int(input('Enter a number: '))
print('Your number is between 2 and 5?')
print(guess>2 and guess<5)
 
Enter a number: 3
Your number is between 2 and 5?
True
In [26]:
print(not True)
print(not False)
print(not 3<5) # It is not the case that 3 is less than 5
 
False
True
False
In [30]:
# 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?
 
True
False
False
False
False
In [31]:
# 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?
 
True
True
True
False
True
 

四、【IF语句】

In [24]:
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.')
 
What is your favourite number? 33
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.

In [25]:
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")
 
44
The letter 'e' occurs 4 times
 

continue跳到循环的下一迭代

In [40]:
i = 0
while i < 10:
    i += 1
    if i == 5:
	    continue
    print(i)
print('Finished')
 
1
2
3
4
6
7
8
9
10
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 完全脱离循环

In [26]:
i = 0

while i < 10:
    i += 1
    if i == 5:
	    break
    print(i)
    
print('Finished')
 
1
2
3
4
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.

 

保持程序持续运行

In [44]:
while True:
    name = input('What is your name? (Enter x to stop) ')
    if name == 'x':
        break
    print('Hello', name)
 
What is your name? (Enter x to stop) 23
Hello 23
What is your name? (Enter x to stop) 4
Hello 4
What is your name? (Enter x to stop) x
 

六、【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”。

 

1、程序在运行时只能打开有限数量的文件,若超出限制,会报错:

Too many open files

2、with可确保资源使用完以后关闭:

In [47]:
# 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)
 
some text
 

3、read()

文本的最后一行时没有\n的

(1)readline()

In [75]:
# 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
 
Line 1: Some text

Line 2: Some more text
True
False
 

read()和readline()方法是累积的——在文件关闭之前,read方法将跳过任何已经使用对read()或readline()的早期调用读取的内容。因此,例如,如果read()访问整个文件,任何后续的read()或readline()调用都将返回空字符串。

In [49]:
# 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 == "")
 
True
True
 

(2)readlines()

In [74]:
# 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
 
['Line 1: Some content\n', 'Line 2: ...\n', 'Line 3: Last line']
 

3、writelines()

列表中的每一行都应以换行符(' \n ')结尾,否则writelines()会将内容连接成一行。

In [4]:
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='')  #用这种办法可以取消空行
 
Line 1: The cat

Line 1: The cat
Line 2: sat on

Line 2: sat on
Line 3: the mat
Line 3: the mat
 

4、for语句遍历

In [78]:
# 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
 
Line 1: Some content

True
Line 2: ...

True
Line 3: Last line
False
 

七、[List】

1、取值

In [4]:
# 倒序取值

x = ['a', 'b', 'c', 'd', 'e']
print(len(x))
print(x[-1])    # x[len(x)-1]=x[5-1]=x[4]---即最后一个数
print(x[-2])
 
5
e
d
In [32]:
# 取一部分 [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]) # 反向&隔一个取一个
 
x[1:3]= ['b', 'c']
x[1:-1]= ['b', 'c', 'd']
x[:3]= ['a', 'b', 'c']
x[1:]= ['b', 'c', 'd', 'e']
x[:]= ['a', 'b', 'c', 'd', 'e']
['a', 'c', 'e']
['a', 'd']
['e', 'd', 'c', 'b', 'a']
['e', 'c', 'a']
 

2、判断元素是否存在 + 查找元素出现的次数 + 查找元素位置

In [37]:
# 判断数字或字符是不是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))
 
'c' is not in the list
2
3
2
 

3、反向

In [18]:
# list反向 ---- .reverse()

x = ['dog', 'cat', 'mouse', 'horse', 'goat']
x.reverse()
print(x)
 
['goat', 'horse', 'mouse', 'cat', 'dog']
 

4、添加元素

In [19]:
# 在结尾添加 ----.append()

x = ['a', 'b', 'c', 'd', 'e']
x.append('f')
print(x)
 
['a', 'b', 'c', 'd', 'e', 'f']
In [20]:
# 自选位置添加 ----.insert(位置,添加的内容)

x = ['a', 'b', 'c', 'd', 'e']
x.insert(2, 'x')
print(x)
 
['a', 'b', 'x', 'c', 'd', 'e']
 

5、拼接两列表

In [23]:
# 拼接两个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)
 
['a', 'b', 'c', 'd', 'e', 'x', 'y', 'z']
['a', 'b', 'c', 'd', 'e', 'x', 'y', 'z']
 

6、移除元素

In [15]:
# 移除元素 --- .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)
 
c
x= ['a', 'b', 'd', 'e', 3]
3
x= ['a', 'b', 'd', 'e']
y= ['a', 'c', 'd', 'e']
z= ['a', 'b', 'd', 'e', 'c']
 

7、清空列表 --- .clear()

In [38]:
x = ['a', 'b', 'c', 'd', 'e']
y=x
x.clear()
print('x=',x)
 
x= []
 

8、元素间计算

In [41]:
# 数字型加法
print(sum([1, 3, 7, 8, 7, 5, 4, 6, 8, 5]))

# 字符型加法(无,会报错)
print(sum(['q','q','w','e']))
 
54
 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-41-c5358886f52a> in <module>
      3 
      4 # 字符型加法(无,会报错)
----> 5print(sum(['q','q','w','e']))

TypeError: unsupported operand type(s) for +: 'int' and 'str'
 

9、布尔型返回值

In [42]:
# 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]))
 
True
True
False
True
True
True
False
 

10、排序.sort()

In [44]:
# 从小到大排序

x = [1, 5, 4, 2, 3]
x.sort()
print(x)

x = ['c', 'a', 'e', 'b', 'd']
x.sort()
print(x)
 
[1, 2, 3, 4, 5]
['a', 'b', 'c', 'd', 'e']
In [41]:
# 从大到小排序

x = [1, 5, 4, 2, 3]
x.sort(reverse=True)
print(x)
 
[5, 4, 3, 2, 1]
In [49]:
# 排序后赋值

x = [1, 5, 4, 2, 3]

y = sorted(x)
print(y)

y = sorted(x, reverse=True)
print(y)
 
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
In [50]:
# 按字母长度排序  (key=len)

x = ['dog', 'chicken', 'mouse', 'horse', 'goat', 'donkey']
x.sort(key=len)
print(x)
 
['dog', 'goat', 'mouse', 'horse', 'donkey', 'chicken']
 

11、遍历列表loop

In [52]:
# 特别注意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)
 
Everything before o:
a
e
i
Everything except o:
a
e
i
u
 

enumerate() 函数

In [42]:
#enumerate() 将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列
#同时列出数据和数据下标

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
print(list(enumerate(seasons, start=1)))       # 下标从 1 开始
 
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
In [43]:
# 多用于循环

vowels = ['a', 'e', 'i', 'o', 'u']
for i, v in enumerate(vowels):
	print('The vowel at index', i, 'is', v)
 
The vowel at index 0 is a
The vowel at index 1 is e
The vowel at index 2 is i
The vowel at index 3 is o
The vowel at index 4 is u
 

range(起点,终点,步长)

包含范围是:[起点,终点)

In [46]:
for i in range(10):
	print(i)
 
0
1
2
3
4
5
6
7
8
9
In [47]:
for i in range(3, 10):
	print(i)
 
3
4
5
6
7
8
9
In [48]:
for i in range(1, 11):
    for j in range(1, 11):
        print(i, 'times', j, 'is', i*j)
 
1 times 1 is 1
1 times 2 is 2
1 times 3 is 3
1 times 4 is 4
1 times 5 is 5
1 times 6 is 6
1 times 7 is 7
1 times 8 is 8
1 times 9 is 9
1 times 10 is 10
2 times 1 is 2
2 times 2 is 4
2 times 3 is 6
2 times 4 is 8
2 times 5 is 10
2 times 6 is 12
2 times 7 is 14
2 times 8 is 16
2 times 9 is 18
2 times 10 is 20
3 times 1 is 3
3 times 2 is 6
3 times 3 is 9
3 times 4 is 12
3 times 5 is 15
3 times 6 is 18
3 times 7 is 21
3 times 8 is 24
3 times 9 is 27
3 times 10 is 30
4 times 1 is 4
4 times 2 is 8
4 times 3 is 12
4 times 4 is 16
4 times 5 is 20
4 times 6 is 24
4 times 7 is 28
4 times 8 is 32
4 times 9 is 36
4 times 10 is 40
5 times 1 is 5
5 times 2 is 10
5 times 3 is 15
5 times 4 is 20
5 times 5 is 25
5 times 6 is 30
5 times 7 is 35
5 times 8 is 40
5 times 9 is 45
5 times 10 is 50
6 times 1 is 6
6 times 2 is 12
6 times 3 is 18
6 times 4 is 24
6 times 5 is 30
6 times 6 is 36
6 times 7 is 42
6 times 8 is 48
6 times 9 is 54
6 times 10 is 60
7 times 1 is 7
7 times 2 is 14
7 times 3 is 21
7 times 4 is 28
7 times 5 is 35
7 times 6 is 42
7 times 7 is 49
7 times 8 is 56
7 times 9 is 63
7 times 10 is 70
8 times 1 is 8
8 times 2 is 16
8 times 3 is 24
8 times 4 is 32
8 times 5 is 40
8 times 6 is 48
8 times 7 is 56
8 times 8 is 64
8 times 9 is 72
8 times 10 is 80
9 times 1 is 9
9 times 2 is 18
9 times 3 is 27
9 times 4 is 36
9 times 5 is 45
9 times 6 is 54
9 times 7 is 63
9 times 8 is 72
9 times 9 is 81
9 times 10 is 90
10 times 1 is 10
10 times 2 is 20
10 times 3 is 30
10 times 4 is 40
10 times 5 is 50
10 times 6 is 60
10 times 7 is 70
10 times 8 is 80
10 times 9 is 90
10 times 10 is 100
In [63]:
for i in range(2):
	for j in range(2):
		for k in range(2):
			print(i, j, k)
 
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
 

12、二维数组

In [66]:
# reverse()单独写不针对嵌套的数组,应定位至该数组再reverse(),如下一代码

numbers = [[1,2,3],[3,4,5],[6,7,8]]
print(len(numbers))
print(numbers[0])

numbers.reverse()
print(numbers)
 
3
[1, 2, 3]
[[6, 7, 8], [3, 4, 5], [1, 2, 3]]
In [67]:
# 获取内部嵌套数组的单个值 & 排序

numbers = [[1,2,3],[3,4,5],[5,6,7]]
print(len(numbers[0]))
print(numbers[0][0])
numbers[0].reverse()
print(numbers[0])
 
3
1
[3, 2, 1]
In [50]:
# 所有数字相加

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)
 
[1, 2, 3]
1
2
3
[3, 4, 5]
3
4
5
[5, 6, 7]
5
6
7
36
 

八、Tuples 元组

  • 不可更改
  • 其他操作与list相同
In [88]:
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))
 
5
4
False
2
c
e
('b', 'c')
('a', 'b', 'c', 'd', 'e', 1, 1, 2, 3)
7
True
False
In [22]:
#如果赋值的时候什么都不加,直接默认为tuple

y=1,2,3
print(y)
 
(1, 2, 3)
In [25]:
# 特别注意!!!!!      (单个值)不是tuple

y=10
z=(10)
print(y)
print(z)
 
10
10
 

九、集合

  • 元素的唯一性(同一对象只可包含一个)
  • 无序的,没有索引(例:a[0])
In [56]:
#无序的
vowels = {'b', 'e', 'i', 'o', 'u'}
print(vowels)

#忽略相同对象,只保留第一个
x = {'cat', 'mouse', 'dog', 'cat', 'cat'}
print(x)
 
{'u', 'o', 'b', 'e', 'i'}
{'cat', 'dog', 'mouse'}
In [100]:
# 添加元素

vowels = set()
vowels.add('a')
vowels.add('e')
vowels.add('e') # No error, just not added
print(vowels)


vowels.update('b', 'c')
print(vowels)
 
{'e', 'a'}
{'b', 'e', 'c', 'a'}
In [103]:
# 删除元素

vowels = {'a', 'e', 'i', 'o', 'u'}
vowels.remove('a')
print(vowels)

# 用.discard()删除没有的元素不会报错,用.remove()删除没有的元素会报错
vowels.discard('f') # No error
print(vowels)
vowels.remove('f') # Error
 
{'o', 'u', 'i', 'e'}
{'o', 'u', 'i', 'e'}
 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-103-32e3f818c6a2> in <module>
      8 vowels.discard('f') # No error
      9 print(vowels)
---> 10vowels.remove('f') # Error

KeyError: 'f'
In [105]:
# 清空集合

vowels = {'a', 'e', 'i', 'o', 'u'}
vowels.clear()
print(vowels)
 
set()
In [93]:
#获取长度
print(len({'a', 'e', 'i', 'o', 'u'}))
print(len({}))
 
5
0
In [94]:
#查找元素
names = {'John', 'Bob', 'Alice'}
print('John' in names)
print('Eve' in names)
 
True
False
In [96]:
# 迭代
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())
 
{'cat', 'mouse', 'dog'}
CAT
MOUSE
DOG
O
A
U
I
E
 

并集与交集

In [107]:
#并集

evens = {2, 4, 6, 8}
primes = {2, 3, 5, 7}

#下面三种方式均可
print(evens | primes)
print(evens.union(primes))
print(primes.union(evens))
 
{2, 3, 4, 5, 6, 7, 8}
{2, 3, 4, 5, 6, 7, 8}
{2, 3, 4, 5, 6, 7, 8}
In [108]:
#交集

evens = {2, 4, 6, 8}
primes = {2, 3, 5, 7}

print(evens & primes)
print(evens.intersection(primes))
print(primes.intersection(evens))
 
{2}
{2}
{2}
In [109]:
#两集合之间的差异

evens = {2, 4, 6, 8}
primes = {2, 3, 5, 7}

print(evens - primes)
print(evens.difference(primes))
print(primes - evens)
print(primes.difference(evens))
 
{8, 4, 6}
{8, 4, 6}
{3, 5, 7}
{3, 5, 7}
 

十、字典

  • 无序集合
In [57]:
#定义字典

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)
 
{'Alice': 'a', 'Bob': 1, 'Eve': 2, 'Mallory': 3}
a
{1: 'one', 'two': 2, 3: 3}
In [19]:
# 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']}
Out[19]:
{'Hahn': ['tap', 'rooster'], 'Tisch': ['table'], 'Zug': ['train']}
In [60]:
#key必须是唯一的,多了会被忽略

scores = {
    'Alice': 1,
    'Bob': 1
}

print(scores)

scores = {
    'Alice': 1,
    'Alice': 1
}

print(scores)
 
{'Alice': 1, 'Bob': 1}
{'Alice': 1}
In [12]:
#更新键值

scores = {
	'Alice': 0,
	'Bob': 1,
	'Eve': 2,
	'Mallory': 3,
}
scores['Bob'] = 900
scores['Alice'] += 1
print(scores)
 
{'Alice': 1, 'Bob': 900, 'Eve': 2, 'Mallory': 3}
In [5]:
# 删除key,即删除该组


scores = {
	'Alice': 0,
	'Bob': 1,
	'Eve': 2,
	'Mallory': 3,
}
del scores['Bob']
print(scores)
 
{'Alice': 0, 'Eve': 2, 'Mallory': 3}
In [6]:
# 只输出key值

scores = {
	'Alice': 0,
	'Bob': 1,
	'Eve': 2,
	'Mallory': 3,
}
for key in scores:
	print(key)
 
Alice
Bob
Eve
Mallory
In [87]:
# 获取所有值,一一对应
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)
 
Alice 0
Bob 1
Eve 2
Mallory 3
 

十一、各类型间转换

  • list()
  • tuple()
  • set()
  • dict()
In [128]:
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, 1, 1, 2, 3, 4, 5)
{1, 2, 3, 4, 5}
[1, 2, 3]
(1, 2, 3)
[1, 2, 3]
{1, 2, 3}
In [131]:
# 字典与列表的转换
#(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()))
 
['Alice', 'Bob', 'Eve', 'Mallory']
[('Alice', 0), ('Bob', 1), ('Eve', 2), ('Mallory', 3)]
In [134]:
#(2)列表-->字典
scores = [(1, 'A'), (2, 'B')]
scores_dict = dict(scores)

print(scores_dict)
print(type(scores))
print(type(scores_dict))
 
{1: 'A', 2: 'B'}
<class 'list'>
<class 'dict'>
In [26]:
[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
 
[10, 11, 12, 21, 22, 23, 31, 32, 33, 41, 42, 43]
Out[26]:
(10, 11, 12, 21, 22, 23, 31, 32, 33, 41, 42, 43)
In [31]:
# Singleton dictionary and set, respectively
print(type({'one': 1}))
print(type({'one'}))
# Empty dictionary and set, respectively
print(type({}))        #dictionary
print(type(set()))     #set
 
<class 'dict'>
<class 'set'>
<class 'dict'>
<class 'set'>
In [ ]:
 
posted @ 2021-09-02 23:37  企小鹅同学、  阅读(68)  评论(0)    收藏  举报