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

发表于:2023-10-13 09:16

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Meng    来源:今日头条

  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-循环的代码内容
  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号