1.list
list_demo = [7, 7, 8, 9, 9, 9]
print(list_demo.index(7)) # index 方法返回第一个index
list_demo.sort() # 排序list
list_demo.reverse() # 倒序list
list_demo1 = list_demo.copy() # 复制list
2.matrix
其实就是list嵌套,可以使用双重for遍历,所包含方法与list一致
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0][0])
for row in matrix:
for i in row:
print(i)
1
1
2
3
4
5
6
7
8
9
Process finished with exit code 0
3.for循环实例:随机生成一个固定大小的list,并找到list中最大的数和对应的index
import random
list_demo = []
for i in range(10):
list_demo.append(random.randint(0, 100))
max_num = list_demo[0]
print(list_demo)
for i in list_demo:
if i >= max_num:
max_num = i
print(f"Max_Num = list_demo[{list_demo.index(max_num)}] = {max_num}")
4.for循环实例:删除list中重复的元素
list_num = [1, 1, 2, 3, 4, 5, 3, 1]
list_copy = []
for i in list_num:
if i not in list_copy:
list_copy.append(i)
print(list_copy)
5.tuple
tuple不可变,但是可以多个tuple拼接组合
tuple_demo = (1, 2, 3, 1, 1) # tuple不可变
tuple_demo.index(1)
tuple_demo.count(1)
coordinates = (1, 2, 3)
x, y, z = coordinates # python优势,string\list\tuple等都可以
msg = 'string'
a, b, c = msg[0:3]
print()
6.dictionary
{key:value}
dic_demo = {"name": "abc", "age": 25, "is_verified": True, "birth_year": 1998}
print(dic_demo["name"])
print(dic_demo.get("age"))
print(dic_demo.get("1sad4"))
print(dic_demo.get("birth_year"))
print(dic_demo)
abc
25
None
1998
{'name': 'abc', 'age': 25, 'is_verified': True, 'birth_year': 1998}
Process finished with exit code 0
7.dictionary application: Translate the input number into English
input默认是string,可以直接遍历string建立string:string的dictionary,也可以将input变为int,建立int:string的dictionary
define的method是将数字拆分单个数的组成的list
dic_demo = {
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
0: "zero"
}
dic_demo1 = {
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine",
"0": "zero"
}
string_num = input("Please input the numbers:")
# string方法
string_ans = ""
for i in string_num:
string_ans = string_ans+dic_demo1[i]+" "
print(string_ans)
def nums_to_single(nums_demo):
nums_ans = []
if nums_demo == 0:
nums_ans.append(0)
while nums_demo > 0:
nums_ans.append(nums_demo % 10)
nums_demo = int(nums_demo / 10)
nums_ans.reverse()
return nums_ans
# int方法
string_ans1 = ""
int_num = int(string_num)
num_list = nums_to_single(int_num)
for i in num_list:
string_ans1 = string_ans1+dic_demo[i]+" "
print(string_ans1)