python中的一些细节,让你不在迷糊

1、python中变量的数据类型

整型、浮点型、字符串、列表、元组、集合、词典、布尔
为什么要分数据类型?
不同变量类型占用的内存不同,有助于内存碎片化,有效利用。对于变量占用内存小的没必要分配大的数据类型。

2、list和tuple的区别

  • (1)可变和不可变
    可变和不可变指的是对于已经存在的数值可变和不可变,其他没什么区别
list1 = [1,2,3]
t1 = (1,2,3)

list1 += [4]
# t1 += (4)  # (4)是整型
# print(type((4)))
t1 += (4,)

list1[0] = 10
t1[0] = 2  # 已有的元素是不可变的,但是可以增加

3、list切片索引

list1 = [20, "the", 22.2, "world"]
print(list1[1])
print(list1[0])
# print(list1[10])  # 报错,超出索引
print(list1[-1])

print("----------")
print(list1[1:4])  # [20, "the", "world"]
print(list1[4:1])  # [] 因为有默认步长为1,步长为正数表示索引从小到达,和前面矛盾,所以返回[]
print(list1[4:1:1])  # []
print(list1[1:4:-1])  # []
print(list1[-1:-4:1])  # []

print("----------")
print(list1[:4])  # 默认从0开始[20, 'the', 22.2, 'world']
print(list1[1:])  # 默认到最后['the', 22.2, 'world']
print(list1[::])  # 默认全部切片,步长为1[20, 'the', 22.2, 'world']
print(list1[::-1])  # 因为步长是-1,默认从最后一个到第零个取,逆序 ['world', 22.2, 'the', 20]

print("----------")
print(list1[3:0:-1])  # ['world', 22.2, 'the']
print(list1[3::-1])  # ['world', 22.2, 'the', 20]
print(list1[3:-1:-1])  # []
# 为什么print(list1[3:-1:-1])为[]
print(list1[1:-1])  # ['the', 22.2]
print(list1[1:-2])  # ['the']
print(list1[1:-3])  # [] 所以print(list1[3:-1:-1])为[] 看到步长为负的,可以把索引从右往左0依次增大去思考,"world"索引为0,20索引为3同时索引也为-1

4、list自动截断

list1 = [1,2,3,4,5]
# print(list1[:100])  # [1, 2, 3, 4, 5]
batch = 2
total_batch = len(list1)//batch
for i in range(total_batch):
    data = list1[i*batch: (i+1)*batch]
    print(data)

# 可以利用list自动截断取出最后一部分数据,深度学习中可能会用到
list1 = [1,2,3,4,5,6,7,8,9]
batch = 7
total_batch = len(list1)//batch
if len(list1) % batch != 0:
    total_batch = int(total_batch + 1)
for i in range(total_batch):
    data = list1[i*batch: (i+1)*batch]
    print(data)

# 也可以利用numpy函数

# 也可以直接向上取整
list1 = [1,2,3,4,5,6,7,8,9,10]
batch = 3
total_batch = (len(list1)+batch-1)//batch
for i in range(total_batch):
    data = list1[i*batch: (i+1)*batch]
    print(data)

5、list的append和extend

list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1 + list2
list4 = list2 + list1
list5 = list1.append(list2)
list6 = list1.extend(list2)

print(list3)  # [1, 2, 3, 4, 5, 6]
print(list4)  # [4, 5, 6, 1, 2, 3]
print(list5)  # None 实际上list1.append()函数把list改变了
print(list6)  # None

list1 = [1,2,3]
list2 = [4,5,6]
list1.append(list2)  # [1, 2, 3, [4, 5, 6]]
print(list1)
list1 = [1,2,3]
list2 = [4,5,6]
list1.extend(list2)  # [1, 2, 3, 4, 5, 6]
print(list1)

6、更改list长度的要注意,新建一个list,不要再原始上操作

list1 = [1,2,3,4,5,6,7,8,9]
for i in list1:
    if i%3 == 0:
        # list1.pop()  # 根据下标移除
        list1.remove(i)  # 根据元素移除
print(list1)

# 上面的根据元素删除没什么问题,但是下面根据下标删除就报错超出索引,因为list的长度再变少
list1 = [1,2,3,4,5,6,7,8,9]
for i in range(len(list1)):
    if list1[i] % 3 == 0:
        list1.remove(list1[i])  # 根据元素移除
print(list1)

# 一般新建一个新的list来防止报错
list1 = [1,2,3,4,5,6,7,8,9]
list2 = []
for i in range(len(list1)):
    if list1[i] % 3 != 0:
        list2.append(list1[i])
print(list2)

7、set

  • 特性:不重复性无序性
# 无序性
set1 = {"hello",1,2,3,4,0,"the",32,14}
print(set1)  # {0, 1, 2, 3, 4, 32, 'the', 14, 'hello'}

# 可以用来去重
list1 = [1,2,3,4,1]
list1 = list(set(list1))
print(list1)

8、dict

list1 = [1,2,5,3,4,23,9]
list2 = sorted(list1)
print(list2)

dict1 = {1:"zhang", 22:"wang", 27:"li"}
for i in dict1:
    print(i)
for i in dict1.keys():
    print(i)
for i in dict1.values():
    print(i)
for key,value in dict1.items():
    print(key, value)

# 对键进行排序
print(sorted(dict1,reverse=True))

9、lambda的简单使用以及sorted的排序

# lamdba简单使用
y = lambda x: x+1
print(y(1))  # 2

# 嵌套
y1 = lambda x: x+1
y2 = lambda i: y1(i)**2
print(y2(2))  # 9

# 1~n的和
res = lambda i: sum([_ for _ in range(0, i+1)])
print(res(10))  # 55

# 第一种方式遍历dict键值对
dict1 = {"a":1, "b":2, "c":3, "d":4}
for key in dict1:
    print(key, dict1[key])
# 第二种遍历dict键值对
for key,value in dict1.items():
    print(key, value)
# sorted函数对dict的值从大到小排序
li = sorted(dict1.items(), key=lambda x:x[1], reverse=True)  # [('d', 4), ('c', 3), ('b', 2), ('a', 1)]
# 有一个二元tuple,按照中间位置进行从大到小排序
t = ((1,0,2), (2,6,10), (99,1,30), (3,-1,33))
li1 = sorted(t, key=lambda x:x[1], reverse=True)  # [(2, 6, 10), (99, 1, 30), (1, 0, 2), (3, -1, 33)]
# 对二元tuple按照三个值中最大的从大到小排序
li2 = sorted(t, key=lambda x:max(x), reverse=True)  # (99, 1, 30), (3, -1, 33), (2, 6, 10), (1, 0, 2)]
# 可以尝试一个文本txt,统计词频并且按照词频从大到小排序

10、布尔类型的相关点

a = 10
b = 20
print(a==b)
print(type(a==b))
print(int(a==b))  # 非零即真
print(int(bool(-1)))

11、 判断list对应位置上有几个相等的元素

# 方法一
list1 = [1,2,4,5]
list2 = [1,2,3,7]
num = 0
for i,j in zip(list1, list2):  # zip()函数有同时遍历的意思
    if i == j:
        num += 1
    else:
        pass
print(num)  # 2
print(list1==list2)
# 方法二
import numpy as np
n1 = np.array([1,2,4,5])
n2 = np.array([1,2,3,7])
print(n1==n2)  # [ True  True False False]
print(sum(n1==n2)/len(n1)*100)  # 准确率 50%

if n1 == n2:  # 报错Use a.any() or a.all(),因为np里array不是像list一样全部拿来比较的
    print("相等")
else:
    print("不相等")
  • 以后代码中也常会出现逻辑错误:只写if不写else接for容易出错,所以写if最好写else pass,不然逻辑错很难找

12、导包规则

  • import XX pip install
    xx可以直接导;本地当前运行统计目录文件代码也可
  • from XX import X
    注意XX文件中的主函数下面的变量什么的导不进来
  • import XXY as XY
    XXY起别名为XY,原先的名字XXY作废
  • from XX import *
    不建议这样导包,如果很多个都这样导包,万一不小心用到了包里主函数的变量报错,都不知道是哪个包导入出错

报错:no module常见原因四个:

  • 没有导包
  • 本地缺少包文件
  • python环境错了
  • 包的版本不对

主函数里面的东西只对当前文件测试有用,别的文件调用时不会调用到当前文件的主函数内容

13、函数中易错点

  • 同级别的代码空格一样不会报错,否则会报错
def fun1():
  print("hello")
  if True:
        print("hahha")
        print("heihei")


def fun2():
  print("hello")
  if True:
        print("hahha")
          print("heihei")  # 会报错


if __name__ == '__main__':
    fun1()
    fun2()
  • 局部变量使用易错点
def swap(a, b):
    a, b = b, a
    print("a=%d, b=%d" % (a, b))


if __name__ == '__main__':
    a = 10
    b = 20
    swap(a, b)
    print("a=%d, b=%d" % (a, b))  # swap中的a和b是局部变量,不会影响这里的a和b,所以a还是10,b还是200
  • 只运行当前文件时,main函数下面的变量是全局变量,只有其他文件调用此文件时main下面的变量就是局部变量调用不到了
def swap():
    print("a=%d, b=%d" % (a, b))


if __name__ == '__main__':
    a = 10
    b = 20
    swap()
  • 分函数中修改全局变量
def swap():
    print("a=%d, b=%d" % (a, b))
    a = 99  # 会报错
    b = 100


def fun1():
    global a, b
    print("a=%d, b=%d" % (a, b))
    a = 99
    b = 100


if __name__ == '__main__':
    a = 10
    b = 20
    # swap()
    fun1()

14、字符串string常用函数

  • replace() 有返回值,不会改变原先的字符串
str1 = "fhdia"
str2 = str1.replace("a", "111")  # replace() 不会改变原来的字符串
print(str2)
  • strip() 有返回值,不会改变原先的字符串,去掉字符串左右的空格
  • lstrip() 去掉左边的空格
  • rstrip() 去掉右边的空格
str1 = " fhdia "
str3 = str1.strip()  # strip()函数不会改变原先的字符串,去掉字符串左右的空格
print(str1)
print(str3)

补充:nupy.shuffle random.shuffle也都是没有返回值的


posted @ 2022-12-19 08:46  时光如你般美好  阅读(30)  评论(0编辑  收藏  举报