python基础-day07

接着前面的编码问题,继续,

一篇文章在硬盘上存储的形式是,bytes,

打开的话,需要转换为unicode形式,这里需要解码decode,即编码的逆过程,

比如decode('gbk') 或 decode('utf-8').

那怎么知道解码哪种呢?


现在所学的东西,只够用一年半,新东西,需要继续学习,


一个蛮经典的面试题,

s = (1)
s1 = (1,)
print(type(s),type(s1))
#运行结果
#<class 'int'> <class 'tuple'>
s = ' '
if s:
    print(1)
#会打印出来1,结论:空白字符串,逻辑判断是True


关于list的操作,

在循环一个列表的时候,最好不要进行删除的动作,准确的说,增加也最好不要,

因为这样会引起索引的改变,你不知道什么时候可能就出错了,

给你三个方式,如果你真的需要更改列表中的值,

第一种方式
li = [11,22,33,44,55]
for i in range(len(li)-1,-1,-1):
    if i % 2 == 1:
        del li[i]
print(li)
#运行结果,
#[11, 33, 55]
#从后面开始循环往前删,因为这样的话,你更改的值在后面,而循环迭代是往前,不会影响到,
第二种方式,用del切片的方式,
li = [11,22,33,44,55]
del li[1::2]
print(li)
#打印结果
#[11, 33, 55]
#第三种方式,通过一个空的列表来中转下,
li = [11,22,33,44,55]

l1 = []
for i in range(len(li)):
    if i % 2 == 0:
        l1.append(li[i])
li = l1
print(li)
# 上面和下面的区别是,for循环中,一个迭代的是下标,一个迭代的是列表中的值,
l1 = []
for i in li:
    if li.index(i) % 2 == 0:
        l1.append(i)
li = l1
print(li)
li = [11,22,33,44,55]
for i in li:
    print(li)
    li.remove(i)
    print(li)
print(li)
#通过remove(),再来看看list()
#运行结果
# [11, 22, 33, 44, 55]
# [22, 33, 44, 55]
# [22, 33, 44, 55]
# [22, 44, 55]
# [22, 44, 55]
# [22, 44]
# [22, 44]

字典个一个方法,

def fromkeys(*args, **kwargs):  # real signature unknown
    """ Returns a new dict with keys from iterable and values equal to value. """
    pass

# dic = dict.fromkeys("abcdefg",'ww')
# print(dic)
#运行结果如下,函数的用法自己看英文,
#{'c': 'ww', 'f': 'ww', 'g': 'ww', 'a': 'ww', 'd': 'ww', 'e': 'ww', 'b': 'ww'}

dic = dict.fromkeys("haha", [])
print(dic)
dic['h'].append(11)
print(dic)
#运行结果,这有个坑,我对一个进行追加,两个都追加了,本质原因是它们是同一个,
# {'h': [], 'a': []}
# {'h': [11], 'a': [11]}


dic = {'k1':'value1','k2':'value2','name':'wusir'}
# 将含有字母k的关键字对应的,键值对,删除,

# 字典在循环中进行增删,存在与list同样的问题,
# RuntimeError: dictionary changed size during iteration
for i in dic:
    if 'k' in i:
        del dic[i]
count = 0
for i in dic:
    dic[i+str(count)] = dic[i]
    count += 1
#报错,RuntimeError: dictionary changed size during iteration
#字典在循环中进行增删,存在与list同样的问题,是这段代码想告诉我们的,

#下面这段代码,通过与前面list相似的方式,进行更改操作,
#通过一个列表记录要修改的地方,然后后面再进行更改,
l1 = []
for i in dic:
    if 'k' in i:
        l1.append(i)

for i in l1:
    del dic[i]
print(dic)


数据类型转换,

就是int,str,list,tuple等数据类型之间的相互转换,

通过join(),split(),list(),int(),str()等方法实现,

我这里就这样简单的记录下有这个知识点吧,



集合set的特点,内部元素不重复,且是无序的,

主要用在爬虫和运维开发,其它领域要用的话,恐怕就是面试题了,

主要用来去重和数据关系的测试

s = {[1,2,3]}
print(type(s))
#运行结果,报错
#TypeError: unhashable type: 'list'
#总结:集合内的元素得是可hash的

s = {1,3,40}
print(hash(s))
#运行结果
#TypeError: unhashable type: 'set'
#总结:集合set本身是不可哈希的,

关于set去重来个题外话,

你通过set()可以很简单的实现去重,

你如果通过自己写算法,首先底层的算法是通过C的,就这一点你自己通过python写的就比他慢,

其次这些写python的人,本身就已经写的很高效了,


集合操作:

增加:

def add(self, *args, **kwargs):  # real signature unknown
    """
    Add an element to a set.

    This has no effect if the element is already present.
    """
    pass

def update(self, *args, **kwargs): # real signature unknown
    """ Update a set with the union of itself and others. """
    pass

删除:

def remove(self, *args, **kwargs):  # real signature unknown
        """
    Remove an element from a set; it must be a member.

    If the element is not a member, raise a KeyError.
        """
    pass


def pop(self, *args, **kwargs):  # real signature unknown
    """
    Remove and return an arbitrary set element.
    Raises KeyError if the set is empty.
    """
    pass
# arbitrary:adj. [数] 任意的;武断的;专制的
#
# 集合set删除还有clear和del,
#clear()之后,空集合打印set(),但是集合定义用的是{}花括号,

接着就是集合的相关运算,知道大概就行,用的很少,

直接放老师笔记了,

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
# 交集 & intersection
# print(set1 & set2)
# print(set1.intersection(set2))
#反交集 ^ symmetric_difference
# print(set1 ^ set2)  # {1, 2, 3, 6, 7, 8}
# print(set1.symmetric_difference(set2))  # {1, 2, 3, 6, 7, 8}
#并集 | union
# print(set1 | set2)
# print(set1.union(set2))
#差集
# print(set1 - set2)
# print(set2 - set1)

# set1 = {1,2,3}
# set2 = {1,2,3,4,5,6}
# print(set1.issubset(set2))  # 子集
# print(set2.issuperset(set1))  # set2 是set1的超集

# set1 = {'barry',"wusir"}
# set2 = frozenset(set1)
# print(set2,type(set2))
#特地说下,frozenset(),
#效果就是,集合本身是不能被哈希的,而经过这个处理后,就可以被哈希了,
#也就是说,可以作为字典的键了,你通过hash()函数可以得到它的哈希值!!!


关于深浅拷贝,

>>> l1= [1,2,3,4,5,6]
>>> l2 = l1
>>> id(l1)
1630424480072
>>> id(l2)
1630424480072
>>> #id值一样
>>> #总结:使用=赋值运算符,指向的是同一个内存地址,那是否可以说:python之中一切皆是引用?


copy(),浅拷贝,即拷贝的结果,第一层相对于拷贝源是独立的,但是内部还有第二层的话,就是同一个非独立的了

使用方法l2 = l1.copy(),实际用的也少,估计也就面试会考这些,


>>> l1 = [1, 2, [1, 2, 3], 4]
>>> l2 = l1[:]
>>> id(l1)
1630470638216
>>> id(l2)
1630470635144
>>> l1[2].append(9)
>>> print(l1)
[1, 2, [1, 2, 3, 9], 4]
>>> print(l2)
[1, 2, [1, 2, 3, 9], 4]
>>> #总结:[]切片相当于copy浅拷贝,拷贝的新值第一层是独立与拷贝源的,第二层就不是了,是同一个对象,
>>> 这里说的是切片全部,即[:],如果是切片一部分,也是两个独立的部分,
>>> l1 = [1,2,3,4,5]
>>> l2 = l1[0:2]
>>> id(l1)
1630471376968
>>> id(l2)
1630470635144
>>> l1.append(99)
>>> l1
[1, 2, 3, 4, 5, 99]
>>> l2
[1, 2]
>>> #这里讨论的是切片部分
>>> #结果就是,两部分是独立的,增加数据对另一个数据也没影响
>>> 

深拷贝,需要导入copy,import copy,

使用方法l2 = copy.deepcopy(l1),前面的copy代表模块,后面是它调用的方法,


再来谈谈编码,

工作中,gbk是很常用的一种编码,不过都在往utf-8过渡,

encode()是编码,decode()是解码,

关于两个函数参数的填写,如果你编码encode()是gbk,对应的解码decode()也得是gbk,


def decode(self, *args, **kwargs):  # real signature unknown
    """
    Decode the bytes using the codec registered for encoding.

      encoding
        The encoding with which to decode the bytes.
      errors
        The error handling scheme to use for the handling of decoding errors.
        The default is 'strict' meaning that decoding errors raise a
        UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
        as well as any other name registered with codecs.register_error that
        can handle UnicodeDecodeErrors.
    """
    pass


def encode(self, encoding='utf-8', errors='strict'):  # real signature unknown; restored from __doc__
    """
    S.encode(encoding='utf-8', errors='strict') -> bytes

    Encode S using the codec registered for encoding. Default encoding
    is 'utf-8'. errors may be given to set a different error
    handling scheme. Default is 'strict' meaning that encoding errors raise
    a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
    'xmlcharrefreplace' as well as any other name registered with
    codecs.register_error that can handle UnicodeEncodeErrors.
    """
    return b""

最后说一点,如果你想gbk和utf-8相互转换,你得通过unicode进行一个转换,

因为这两种编码都是在unicode编码基础上而来的,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值