使用Python对数据进行操作转换

开发 后端
我们首先定义一个列表 MyList,接着,我们使用字典推导式,创建一个新的字典 MyDict,其中字典的键是从列表 MyList 中获取的每个元素,而对应的值都设置为 None。

1、列表加值转字典

在Python中,将列表的值转换为字典的键可以使用以下代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

myList = ["name", "age", "location"]
myDict = {k: None for k in myList}
print(myDict)

输出:

{'name': None, 'age': None, 'location': None}

在上面的代码中,我们首先定义一个列表 myList,接着,我们使用字典推导式,创建一个新的字典 myDict,其中字典的键是从列表 myList 中获取的每个元素,而对应的值都设置为 None。

如果想让列表中的值对应不同的值,只需在推导式中指定相应的值即可,例如:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

myList = ["name", "age", "location"]
myValues = ["John", 22, "Bei Jing"]
myDict = {myList[i]: myValues[i] for i in range(len(myList))}
print(myDict)

输出:

{'name': 'John', 'age': 22, 'location': 'Bei Jing'}

在上面的代码中,我们创建一个包含键、值的列表,然后使用循环和字典推导式来创建字典,其中列表中的每个值对应于字典中的一个键和一个值。

2、字典键新增值数据

根据上面的代码,对每个键又新增了2条数据,该如何操作。

如果想要在已经存在的字典中为每个键添加多个值,可以将值存储在列表中,然后将列表作为键对应的值,例如:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

myDict = {"name": ["John"], "age": [22], "location": ["Bei Jing"]}

# 为 name 增加两个新值
myDict["name"].extend(["Alice", "Bob"])
print(myDict)

# 为 age 和 location 增加两个新值
myDict["age"].append(25)
myDict["location"].extend(["Shang Hai", "Guang Zhou"])
print(myDict)

输出:

{'name': ['John', 'Alice', 'Bob'], 'age': [22], 'location': ['Bei Jing']}
{'name': ['John', 'Alice', 'Bob'], 'age': [22, 25], 'location': ['Bei Jing', 'Shang Hai', 'Guang Zhou']}

在上面的代码中,我们首先在字典中为每个键初始化一个列表,然后可以使用字典键和列表方法来添加由多个值组成的列表。

3、转换新的字典格式

如何将[{'key': 'name', 'value': 'John'}, {'key': 'location', 'value': 'Bei Jing'}]数据更改为{'name': 'John', 'location': 'Bei Jing'}

可以使用一个循环来遍历列表中的字典,然后将每个字典的键和值提取出来,组成一个新的字典。具体如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

# 原始数据
data = [{'key': 'name', 'value': 'John'}, {'key': 'location', 'value': 'Bei Jing'}]

# 新的字典
new_dict = {}
for item in data:
    key = item['key']
    value = item['value']
    new_dict[key] = value

print(new_dict)

输出:

{'name': 'John', 'location': 'Bei Jing'}

首先定义一个空字典 new_dict,用于存储新的数据。然后使用 for 循环遍历原始数据中的每个字典。在循环中,使用 item['key'] 和 item['value'] 分别获取当前字典的键和值,并使用 new_dict[key] = value 将其存储到新的字典中,最后输出新的字典即可。

4、两组数据比较筛选

有两组数据,list1['code', 'data.totalPage', 'data.type']和list2['code', 'description', 'errCode', 'error', 'msg', 'message', 'success', 'btSuccess', 'btCode', 'btMsg', 'header.mss'],筛选list1里面的元素不存在list2里,则预期的筛选结果为['data.totalPage', 'data.type']。

可以使用列表推导式以及not in语句来实现筛选:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

list1 = ['code', 'data.totalPage', 'data.type']
list2 = ['code', 'description', 'errCode', 'error', 'msg', 'message', 'success', 'btSuccess', 'btCode', 'btMsg', 'header.mss']

result = [ele for ele in list1 if ele not in list2]
print(result)

输出:

['data.totalPage', 'data.type']

其中,列表推导式的语法格式为:[返回值 for in 条件语句],它可以将符合条件的元素一次性生成到一个新列表中。而not in语句则表示不在列表中的元素。因此,上述代码中的列表推导式就是遍历list1中的每个元素ele,如果ele不在list2中,则将其添加到结果列表中。

5、将两段独立代码合并

有两段独立的代码,都有for循环。

hj = HandleJson(data_dict)
res = hj.find_key_path('request')
print(res)
print(type(res))
# request-循环
for count_i, api_i in enumerate(res):
    # request
    json_request = eval(str(data_dict) + api_i)
    # print("json_request " + str(json_request))
    # name
    json_name = eval(str(data_dict) + api_i.replace("request", "name"))
    print("count_i 第 " + str(count_i + 1) + " 个接口")
    print("json_name " + str(json_name))

hj2 = HandleJson(data_dict)
res2 = hj2.find_key_path('response')
print(res2)
print(type(res2))
# response-循环
for count_i, api_i in enumerate(res2):
    # response
    json_response = eval(str(data_dict) + api_i)
    print("json_response " + str(json_response))
    if json_response:
        print("json_response 不为空")
        for count_i_i, api_i_i in enumerate(json_response):
            # print(api_i_i)
            # name
            json_name = eval(str(api_i_i) + str(["name"]))
            print("count_i_i 第 " + str(count_i_i + 1) + " 个接口")
            print("json_name " + str(json_name))

如何将这两段代码合并。

可以使用zip()函数将两个循环的结果压缩在一起,然后在一个for循环中同时遍历两个列表。具体代码如下所示:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

hj = HandleJson(data_dict)
res = hj.find_key_path('request')
res2 = hj.find_key_path('response')
for count_i, (api_i, api_i2) in enumerate(zip(res, res2)):
    # request-循环的代码内容
    # response-循环的代码内容
责任编辑:姜华 来源: 今日头条
相关推荐

2022-08-02 09:32:47

pandas移动计算

2021-08-09 15:00:36

SQL数据库

2017-05-08 15:47:06

2010-07-22 17:25:23

2021-10-22 06:53:45

脱敏处理数据

2009-09-08 16:50:12

使用LINQ进行数据转

2020-07-08 15:10:11

Python数据分析代码

2009-09-28 09:47:55

Hibernate数据

2010-11-12 14:16:21

SQL游标

2010-06-13 15:49:07

IP协议数据报

2018-04-16 12:14:34

数据科学机器学习神经网络

2022-11-02 14:45:24

Python数据分析工具

2010-02-01 10:21:36

Python编码转换

2014-04-03 13:11:07

数据中心雅虎

2018-04-25 13:32:31

数据保护GDPRCommvault

2009-05-13 09:39:00

数据中心网络设备管理

2009-07-29 17:27:23

数据中心CMDBIT

2022-04-08 11:25:58

数据库操作AbilityData

2009-07-16 14:46:48

jdbc statem

2023-11-04 15:46:03

GORMGo
点赞
收藏

51CTO技术栈公众号