使用Python對數(shù)據(jù)進行操作轉(zhuǎn)換
1、列表加值轉(zhuǎn)字典
在Python中,將列表的值轉(zhuǎn)換為字典的鍵可以使用以下代碼:
#!/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,接著,我們使用字典推導(dǎo)式,創(chuàng)建一個新的字典 myDict,其中字典的鍵是從列表 myList 中獲取的每個元素,而對應(yīng)的值都設(shè)置為 None。
如果想讓列表中的值對應(yīng)不同的值,只需在推導(dǎo)式中指定相應(yīng)的值即可,例如:
#!/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'}
在上面的代碼中,我們創(chuàng)建一個包含鍵、值的列表,然后使用循環(huán)和字典推導(dǎo)式來創(chuàng)建字典,其中列表中的每個值對應(yīng)于字典中的一個鍵和一個值。
2、字典鍵新增值數(shù)據(jù)
根據(jù)上面的代碼,對每個鍵又新增了2條數(shù)據(jù),該如何操作。
如果想要在已經(jīng)存在的字典中為每個鍵添加多個值,可以將值存儲在列表中,然后將列表作為鍵對應(yīng)的值,例如:
#!/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、轉(zhuǎn)換新的字典格式
如何將[{'key': 'name', 'value': 'John'}, {'key': 'location', 'value': 'Bei Jing'}]數(shù)據(jù)更改為{'name': 'John', 'location': 'Bei Jing'}
可以使用一個循環(huán)來遍歷列表中的字典,然后將每個字典的鍵和值提取出來,組成一個新的字典。具體如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
# 原始數(shù)據(jù)
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,用于存儲新的數(shù)據(jù)。然后使用 for 循環(huán)遍歷原始數(shù)據(jù)中的每個字典。在循環(huán)中,使用 item['key'] 和 item['value'] 分別獲取當(dāng)前字典的鍵和值,并使用 new_dict[key] = value 將其存儲到新的字典中,最后輸出新的字典即可。
4、兩組數(shù)據(jù)比較篩選
有兩組數(shù)據(jù),list1['code', 'data.totalPage', 'data.type']和list2['code', 'description', 'errCode', 'error', 'msg', 'message', 'success', 'btSuccess', 'btCode', 'btMsg', 'header.mss'],篩選list1里面的元素不存在list2里,則預(yù)期的篩選結(jié)果為['data.totalPage', 'data.type']。
可以使用列表推導(dǎo)式以及not in語句來實現(xiàn)篩選:
#!/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']
其中,列表推導(dǎo)式的語法格式為:[返回值 for in 條件語句],它可以將符合條件的元素一次性生成到一個新列表中。而not in語句則表示不在列表中的元素。因此,上述代碼中的列表推導(dǎo)式就是遍歷list1中的每個元素ele,如果ele不在list2中,則將其添加到結(jié)果列表中。
5、將兩段獨立代碼合并
有兩段獨立的代碼,都有for循環(huán)。
hj = HandleJson(data_dict)
res = hj.find_key_path('request')
print(res)
print(type(res))
# request-循環(huán)
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-循環(huán)
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()函數(shù)將兩個循環(huán)的結(jié)果壓縮在一起,然后在一個for循環(huán)中同時遍歷兩個列表。具體代碼如下所示:
#!/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-循環(huán)的代碼內(nèi)容
# response-循環(huán)的代碼內(nèi)容