python对数据的处理合集——字典、列表...

1.两个列表的数据对比
①list2包含了list1,求出list2多余的值

#coding=utf-8

list1=[1,3,5]
list2=[1,3,5,7,9,11]
list=[]
for i in list2:
    if i not in list1:
        list.append(i)
print(list)

在这里插入图片描述
②求出两个列共同的值

③两个列表合并

#第一种:+
list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list1 + list2

#第二种:append
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for item in list2:
    list1.append(item)
new_list = list1

#第三种:extend
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
new_list = list1

#第四种:列表解析语法
list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = [x for x in (list1, list2)]

2.列表去重

#求出list1不重复的值
list1=[1,3,5,7,9,1,11,2,3]
new_list=set(list1)
print(new_list)

在这里插入图片描述

3. 字典的键转为大写、或者首字母转为大写
①修改键名,普通修改

#把键名name改成Name
my_dict = {'name': '小丽'}
# 将原来的键名映射到新的键名,并添加到字典中;pop是删除键
my_dict['Name'] = my_dict.pop('name')
print(my_dict)

在这里插入图片描述
②键名全部转为大写

my_dict={"name":"小丽","age":18,"sex":"男"}
new_dict={}
for key in list(my_dict.keys()):
    value = my_dict[key]
    newkey =key.upper()
    new_dict[newkey] = value
print(new_dict)

在这里插入图片描述

③键名全部转为首字母大写

my_dict={"name":"小丽","age":18,"sex":"男"}
new_dict={}
for key in list(my_dict.keys()):
    value = my_dict.pop(key)
    newkey =key.title()
    new_dict[newkey] = value
print(new_dict)

在这里插入图片描述

4.字典合并新的字典
①ChainMap

data1={"name":"小丽","age":19,"sex":"女"}
data2={"familys":8}
new_data=dict(ChainMap(data1, data2))
print(new_data)

在这里插入图片描述
②深拷贝deepcopy

data1= {"name": "xiaoming", "age": 27}
data2= {"gender": "male"}
from copy import deepcopy
newdata = deepcopy(data1)
newdata.update(data2)
print(newdata)

在这里插入图片描述
③普通copy更新

d1 = {'name': 'revotu', 'age': 99}
d2 = {'age': 24, 'sex': 'male'}
d = dict(d1)
#更新后,age拿的是d2的值
d.update(d2)
print(d)

在这里插入图片描述

你可能感兴趣的:(python,开发语言)