基础数据类型的坑和集合及深浅copy

一、基础数据类型的坑:

元组:

如果一个元组中,只有一个元素,且没有逗号,则该"元组"与里面的数据的类型相同。

# 只有一个数据,且没有逗号的情况:
print(tu1,type(tu1))  # 156 <class 'int'>
tu2 = ("expected")
print(tu2,type(tu2)) #  expected <class 'str'>

那么,在只有一个元素的情况下,如何让元组成其为元组呢?方法就是,在数据的后面,加一个逗号。

#在只有一个数据的情况下,后面加逗号,就实现了元组仅有一个数据时候,也是元组。
tu1 = (123,) print(tu1,type(tu1)) # (123,) <class 'tuple'> tu2 = ('kitty',) print(tu2,type(tu2)) # ('kitty',) <class 'tuple'>

列表:

## 列表与列表可以相加
l1 = [1,3,5]
l2 = ["h","b","a"]
result = l1 + l2
print(result)     # [1,3,5,'h','b','a']

将列表中,索引为奇数的元素,全部删除掉。

## 将列表中索引为奇数的元素,全部删除掉
ls = [00,11,22,33,44,55,66,77]
# 方法一:切片 + 步长
# del ls[1::2]
# print(ls) # [00,22,44,66]
#
# ls = [00,11,22,33,44,55,66,77]
# for i in range(len(ls)):
#     if i % 2 == 1:
#         ls.pop(i)    #  IndexError: pop index out of range
# print(ls)
# 在循环一个列表时,如果对列表中的元素进行删除操作,它后面的所有元素就会向前进一步,导致后面元素的索引发生变化,
# 因此就抛出了错误:IndexError: pop index out of range
# 方法二:将原列表中的索引为偶数的元素,追加到另外一个空列表中,然后再把新新列表 赋值给原列表
# tmp_list = []
# for i in range(len(ls)):    # range() 顾头不顾尾, 在for 循环中, in 后面的表达式,只在循环开始时,执行一次
#     if i % 2 == 0:
#         tmp_list.append(ls[i])
# ls = tmp_list
# print(ls)

# 方法三:倒着删除,即从列表的后面,向前面方向删除,这向前面未删除元素,索引不会变,不会导致索引超出范围

# for index in range(len(ls)-1,-1,-1):  # range(start,end,step)
#     if index % 2 == 1:
#         ls.pop(index)
# print(ls)

# 方法四:在第一次循环过程中,将奇数索引元素,赋值一个标记值 ,然后统计列表,标记值的数量 ,通过循环移除
for index in range(len(ls)):
    if index % 2 == 1:
        ls[index] = "mark_delete"
counts = ls.count("mark_delete")
for count in range(counts):
    ls.remove("mark_delete")    # remove()方法,删除找到的第一个元素
print(ls)

 字典:

 fromkeys() 

## 字典
# fromkeys() 这个方法,即是一个类方法,dict类,可以调用 ,也是一个对象方法,对象也可以调用
dic = dict.fromkeys(['a','b','c'])  # 返回一个新字典 通过 来自迭代对象的key, 默认value为None
print(dic)  # {'a': None, 'b': None, 'c': None}
dic = dict.fromkeys(['a','b','c'],15238)
print(dic)  #  {'a': 15238, 'b': 15238, 'c': 15238}

dic_src = {'name':'chris','age':18,'job':"IT"} print(dic_src) # {'name': 'chris', 'age': 18, 'job': 'IT'} new_dic = dic_src.fromkeys(dic_src) # 如果迭代对象是dict即字典,取得的key print(new_dic) # {'name': None, 'age': None, 'job': None}

陷井: new2_dic = dic_src.fromkeys(dic_src,['jeans']) print(new2_dic) # {'name': ['jeans'], 'age': ['jeans'], 'job': ['jeans']} print(id(new2_dic['name'])) print(id(new2_dic['age'])) print(new2_dic['name'] is new2_dic['age']) new2_dic['name'].append('skr') # 对于对象,如果元素的值一个对象,并且相同的话,内存中会共享一份,因此改共享对象中的内容时,其它也会也 print(new2_dic) # {'name': ['jeans', 'skr'], 'age': ['jeans', 'skr'], 'job': ['jeans', 'skr']} new2_dic['name'] = 'aaa' # 现在不是修改键 对应对象中的内容,而是将键的值修改别的对象,对原来键 的值所对应的对象没有影响,因此不影响其它元素 print(new2_dic) # {'name': 'aaa', 'age': ['jeans', 'skr'], 'job': ['jeans', 'skr']}

 创建字典的三种方式:

  dic  = { 'name':'chris','age':18,'job':'iT'}

  dic = dict(  { 'name':'chris','age':18,'job':'iT'} )     # 通过构造函数,实例化一个对象

  dic  = dict.fromkeys(['name','age','job'],'default')

字典循环中的坑:

## 删除字典中 键 包含 'k'的键,的键值对
dic = {'key1':"value1",'key2':'value2','k3':'value3','name':'chris','manager':'jiayong'}
# for k in dic:     # RuntimeError: dictionary changed size during iteration
#     if 'k' in k:
#         dic.pop(k)
# print(dic)
## 报错,字典在循环过程中,不能改变字典的大小
## 方法,不循环字典,将字典的所有key取出,放到列表,循环列表,删除字典元素
keys = list(dic)
# print(keys)
for key in keys:
    if 'k' in key:
        dic.pop(key)
print(dic)       #  {'name': 'chris', 'manager': 'jiayong'}

 数据类型转换:

  int  str  bool

  int   ----> str

     str(integer)

 str ------> int

      int(str)      # 将字符串转换为整型,前提条件字符串由数字字符组成

int  ---> bool   非零即True,零即False

bool --> int  True为1,False为0

dict.keys()   dict.values()  dict.items()  list()

tuple <----> list

dict -------> list

dic = {"name":'chris',"age":18}
print(list(dic))  #  ['name', 'age']

class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""


ls = [['a','b']] print( dict(ls) ) # {'a': 'b'} l1 = ['a','b'] # print(dict([l1])) # {'a': 'b'} 可见将列表,转换为dict ,是有一定条件的

 str 《------》 list

# str <---> list
str = 'abcef'
ls = list(str)
print(ls)  #  ['a', 'b', 'c', 'e', 'f']
ls = ['a', 'b', 'c', 'e', 'f','h','j']
newStr = "".join(ls)
print(newStr)

   0 "  [] () {} set() ---> bool False

二、集合

### && 集合是无序的,集合的中的数据必须是不可变数据类型(即可哈希类型),但集合本身是可变类型,集合具有天然的去重功能,没有重复数据
##集合的创建,集合与字典都是由大括号或花括号包围起来的,区别是字典中的元素是键值对,而集合中是一个一个的元素
set1 = set({1,3,5,'a','chris',(1,2)})
set2 = {1,3,6,'chris',('a',1)}
print(set1)
print(set2)
print(set2)

# set3 = {1,[1,3,3]}  # 因为[1,3,3]列表是可变数据类型,把以报错了 TypeError: unhashable type: 'list'
## 集合具有天然的去重功能
set5 = {11,1,3,3,98,8}
print(set5)  #  {8, 1, 98, 3}
# 集合的增
set5.add(159)
print(set5)

# update()方法,迭代着增加
'''
PEP8代码规范

    1、单独一行的注释:# + 1空格 + 注释内容

    2、代码后跟着的注释:2空格 + # + 1空格 + 注释内容

'''
set5.update("ROOT")   # 只是对集合进行操作,没有返回值
# 这是一行注释
print(set5)      # {'O', 1, 98, 3, 'R', 8, 'T', 159}
# #删除
set5.pop()         # 移除并返回任意一个集合元素
print(set5)
set5.remove(159)   # 移除指定的元素
print(set5)
set5.clear()        # 清空集合中的所有元素
del set5            # 从内存级别删除整个set5集合

set1 = {1,2,3}
set3 = frozenset(set1)
print(set3) # 不可变的数据类型。 **

set5 = {set3:"这是一个frozenset集合"}  # {frozenset({1, 2, 3}): '这是一个frozenset集合'}

print(set5)  

 

 三、深浅copy

1.题
  把列表中所有姓周的人的信息删掉(升级题 :此题有坑,请慎重):
  lst = [ '周老二','周星星','麻花藤','周扒皮' ]
  结果:lst = ['麻花藤']
'''
# 方法一:
# lst = [ '周老二','周星星','麻花藤','周扒皮' ]
# tmp_lst = []
# for e in lst:
#     if '周' not in e:
#         tmp_lst.append(e)
# lst = tmp_lst
# print(lst)
# 方法二:
# lst = [ '周老二','周星星','麻花藤','周扒皮' ]
# for i in range(len(lst)-1,-1,-1):   # range()方法只会执行一次,谨记
#     if '周' in lst[i]:
#         lst.pop(i)
# print(lst)
# 方法三:
# lst = [ '周老二','周星星','麻花藤','周扒皮' ]
# for i,e in enumerate(lst):  # 用到了分别赋值
#     if '周' in e:
#         lst[i] =  'delete'
# for count in range( lst.count('delete')) :
#     lst.remove('delete')
# print(lst)
# 方法四:
# for i in lst[:]:   # 切片是浅拷贝
#     if '周' == i.strip()[0]:
#         lst.remove(i)
# print(lst)
原文地址:https://www.cnblogs.com/chris-jia/p/9459491.html