2D lists
数字矩阵matrix
[
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
[1, 2, 3] 代表一个list
2 是这个矩阵中list的一个item
如果要访问这个list中的2这个item,如何表示呢
matrix [0][1] dd
- list Methods的operations运算符, list——[5, 2,1, 7, 4]
- 增
- -append 在list尾部添加项目, 比如 numbers.append(20)
- -insert 在指定位置index前添加项目 比如numbers. insert(0, 10)
- 删
- -remove 删除指定列表中的项目 , 比如 numbers.remove(5) 是指从列表中删除项目5
- -clear 删除列表中全部项目, 比如 numbers. clear(), 全部删除
- -pop 删除列表中最后一个项目, 比如numbers. pop()
- 查
- -index 查询列表中某项目对应的序号, 比如numbers.index(5), print输出就是0
- -in 查询某数字或项目是否在字符串中,如果在返回布尔值TRUE,否的话FALSE
- -count 查询某列表中单一项目的个数或出现的次数,比如print(numbers.count(5))= 2
- -sort 给列表中的数字或者字符排序 默认排序是升序ascending
- -reverse 降序排列, 比如-numbers. reverse()
- -copy 列表复制,生成独立的仿制列表。
- 增
练习-删除列表中重复的数字
# 换句话说,意思是,要生成一个新的列表,给这个新列表取一个变量,当就列表中的数字不在新列表中时,就把旧的列表中的数字增加到新列表中append()
numbers = [2, 2, 4, 7, 4, 8, 2, 6, 1] 所以运行代码为:
numbers = [2, 2, 4, 7, 4, 8, 2, 6, 1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
元组tuple()
# 跟列表[]类似,但是元组无法修改(增加、删除、改变),可以计数count还有挑序号index
如果你不希望别人更改你的列表,就最好用元组,而不是用方括号
元组开箱 unpacking
coordinates = (1, 2, 3)
x = coordinates[0]
y = coordinates[1]
z = coordinates[2]
x, y, z = coordinates
除了元组,列表也可以用来开箱
dictionary词典容器
value pair 数值对
词典中每一个key应该是唯一的
get(x, default value)
最大的作用是用来做映射mapping
words = {
":)" : “😁”
“:(”:“😞”
}
以上映射代表:数值对,value Pair
message = input(">")
words = message.split(' ')
emojis = {
":)": "😊",
":(": "😞"
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
print(output)
步骤拆解
1 先定义用户看到的光标,用来给用户输入语句。
2 如果输入的是多个词,并保留空格,需要将不同的单词拆开,所以要用到split。
3 用词典来映射,变量,等号,花括号
4 定义输出的变量output, 这里用到For循环语句,当输入的词为词典中的词时,这是获取这个词然后加上空格。 如果输入的词为两个,这时为X + Y+ . 如果输出的词不在词典中,那么就保留这个词。 因此表达式是output += emojis.get(word, word)+ " "