做题中忘记的一些 python 小知识(2)
8. 字典
- 在 python 3.5 之后的打印会按着字母顺序排列出来
- 字典查找速度比较快
- key 只能放不可修改的东西 bool int float tuple str ,list 不能作为 key 进行修改
(1) 删除字典中的键值对
pizza={"hhh":"djijifj","aaa":"okoko"}
del pizza['hhh']
pizza
// 输出 {'aaa': 'okoko'}
(2) 清空字典
pizza.clear()
pizza
// 清空字典
7. for循环和while循环后的else
如果在循环里遇到了break
就不会走后面的else
如果没遇到break,就会走后面的else
for i in range(10):
print(i)
if i == 5:
break
else:
print("no break")
// 输出
// 0
// 1
// 2
// 3
// 4
// 5
for i in range(10):
print(i)
if i == 15:
break
else:
print("no break")
// 输出
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// no break
6. 复制 list 的方法
a = [1,2,3]
b = a
c = a.copy()
d = a[:]
e = list(a)
print(a)
print(b)
print(c)
print(d)
print(e)
// 输出们
// [1, 2, 3]
// [1, 2, 3]
// [1, 2, 3]
// [1, 2, 3]
// [1, 2, 3]
5. list
(1) list 里可以放不同的元素
my_list=[1, 2, “22”, “xby”]
(2) 删除列表元素
del my_list[0] // 删除列表中第0个元素
del my_list[3:] // 将第3个到最后的都删了
my_list.remove("22") // 删除指定的元素
(3) 使用 + ,将两个 list 连起来
my_list = [1, 2, "22", "xby"]
my_list = my_list + my_list
my_list
// 输出 [1, 2, '22', 'xby', 1, 2, '22', 'xby']
(4) 使用 index 得出元素在列表中的位置
my_list.index("xby")
// 可以输出xby的位置
(5) pop()
my_list.pop()
// 将最后一个元素删掉并作为返回值返回,可用一个变量来接收
// 也可以使用my_list.pop(0)
// 将第0个元素pop掉
4. sort 和 sorted
- The list method sort() sorts the list itself, in place.
- The general function sorted() returns a sorted copy of the list.
- sort和sorted里需要排序的数据类型应该相同.
但是整型和浮点型可以一起比较,int会转换成float再进行比较.
obj_list=[1, 3.14, “sting”]
sorted(obj_list) 和 obj_list.sort()会报错
(1) sort
nums.sort()
sort
// 输出 [1, 2, 3, 4, 5]
nums.sort(reverse=True)
nums
// 输出 [5, 4, 3, 2, 1]
(2) sorted
nums=[1, 4, 2, 5, 3]
sorted_nums = sorted(nums)
print(sorted_nums)
// 输出 [1, 2, 3, 4, 5]
sorted("jidhshfyghuuho1234")
// 输出 ['1','2','3','4','d','f','g','h','h','h','h','i','j','o','s','u','u','y']
3. set 只有 key,没 value。set 中的值唯一。
2. 元组内容不能修改
a = (1,2,3)
a[0] = 4
a
// 会报错 TypeError: 'tuple' object does not support item assignment
// 元组中的内容不能被修改
1. jupyter 将所有输出都打印出来
from IPython.core.interactiveshell import InteractiveShell#
InteractiveShell.ast_node_interactivity="all"
// 使用这两行可以把所有输出都打印出来
from IPython.core.interactiveshell import InteractiveShell#
InteractiveShell.ast_node_interactivity="all"#使用这两行可以把所有输出都打印出来
s = "djfifikif"
s[2:4]
s
// 输出'fi'
// 输出'djfifikif'