首页 > 其他分享 >未验证:字符串解析为字典的九种方法/

未验证:字符串解析为字典的九种方法/

时间:2024-05-30 12:30:37浏览次数:15  
标签:prices item current 字符串 parts 九种 line parsed 字典

我是说直接把字典里的内容变成字符串
然后解析这个字符串为字典
然后才是代码中的计算,我是让你修改代码

将输出字符串解析为字典的九种方法:

方法一:使用正则表达式

import re

parsed_item_prices = {}
current_item = None
for line in output_string.split('\n'):
    if line.startswith("第"):
        current_item = re.search(r':(.+)', line).group(1)
        parsed_item_prices[current_item] = {}
    elif not line.startswith("-") and current_item:
        parts = line.split(":")
        other_item = parts[0].strip()
        ratio = float(parts[1])
        parsed_item_prices[current_item][other_item] = ratio

方法二:使用字符串操作和切片

parsed_item_prices = {}
current_item = None
lines = output_string.split('\n')
for i in range(len(lines)):
    line = lines[i]
    if line.startswith("第"):
        current_item = line.split(":")[1].strip()
        parsed_item_prices[current_item] = {}
    elif not line.startswith("-"):
        parts = line.split(":")
        other_item = parts[0].strip()
        ratio = float(parts[1])
        parsed_item_prices[current_item][other_item] = ratio

方法三:使用字符串操作和索引

parsed_item_prices = {}
current_item = None
lines = output_string.split('\n')
for i in range(len(lines)):
    line = lines[i]
    if line.startswith("第"):
        current_item = line[line.find(":")+1:].strip()
        parsed_item_prices[current_item] = {}
    elif not line.startswith("-"):
        parts = line.split(":")
        other_item = parts[0].strip()
        ratio = float(parts[1])
        parsed_item_prices[current_item][other_item] = ratio

方法四:使用字符串操作和分割

parsed_item_prices = {}
current_item = None
for line in output_string.split('\n'):
    if line.startswith("第"):
        current_item = line.split(":")[1].strip()
        parsed_item_prices[current_item] = {}
    elif not line.startswith("-"):
        parts = line.split(":")
        other_item = parts[0].strip()
        ratio = float(parts[1])
        parsed_item_prices[current_item][other_item] = ratio

方法五:使用字符串操作和判断

parsed_item_prices = {}
current_item = None
lines = output_string.split('\n')
for line in lines:
    if line.startswith("第"):
        current_item = line.split(":")[1].strip()
        parsed_item_prices[current_item] = {}
    elif not line.startswith("-"):
        parts = line.split(":")
        if len(parts) == 2:
            other_item = parts[0].strip()
            ratio = float(parts[1])
            parsed_item_prices[current_item][other_item] = ratio

方法六:使用字符串操作和列表推导

parsed_item_prices = {}
current_item = None
lines = output_string.split('\n')
for line in lines:
    if line.startswith("第"):
        current_item = line.split(":")[1].strip()
        parsed_item_prices[current_item] = {}
    elif not line.startswith("-"):
        parts = [part.strip() for part in line.split(":")]
        if len(parts) == 2:
            parsed_item_prices[current_item][parts[0]] = float(parts[1])

方法七:使用字符串操作和字典get方法

parsed_item_prices = {}
current_item = None
lines = output_string.split('\n')
for line in lines:
    if line.startswith("第"):
        current_item = line.split(":")[1].strip()
        parsed_item_prices[current_item] = {}
    elif not line.startswith("-"):
        parts = line.split(":")
        other_item = parts[0].strip()
        ratio = float(parts[1]) if len(parts) == 2 else None
        if ratio is not None:
            parsed_item_prices[current_item][other_item] = ratio

方法八:使用字符串操作和异常处理

parsed_item_prices = {}
current_item = None
lines = output_string.split('\n')
for line in lines:
    try:
        if line.startswith("第"):
            current_item = line.split(":")[1].strip()
            parsed_item_prices[current_item] = {}
        elif not line.startswith("-"):
            parts = line.split(":")
            other_item = parts[0].strip()
            ratio = float(parts[1])
            parsed_item_prices[current_item][other_item] = ratio
    except IndexError:
        continue

方法九:使用列表操作和迭代器

parsed_item_prices = {}
current_item = None
lines = iter(output_string.split('\n'))
for line in lines:
    if line.startswith("第"):
        current_item = line.split(":")[1].strip()
        parsed_item_prices[current_item] = {}
    elif not line.startswith("-"):
        parts = line.split(":")
        other_item = parts[0].strip()
        ratio = float(parts[1])
        parsed_item_prices[current_item][other_item] = ratio

以上是九种不同的方法,以满足不同的偏好和需求。

标签:prices,item,current,字符串,parts,九种,line,parsed,字典
From: https://blog.csdn.net/weixin_73675558/article/details/139320704

相关文章

  • python-旋转字符串
    问题描述:给定一个字符串(以字符串数组的形式)和一个偏移量,根据偏移量从左到右地旋转字符数组。问题示例:输入str=”abcdefg”,offset=3,输出“efgabcd”。输入str=”abcdefg”,offset=0,输出“abcdefg”。(返回旋转后的字符串) 完整代码如下:a=list(input().split())n=int(inpu......
  • 这种嵌套字典类型的数据,我想把它读取到df里,如何操作?
    大家好,我是皮皮。一、前言前几天在Python最强王者交流群【WYM】问了一个Pandas处理的问题,提问截图如下:原始数据:temp=dict()temp[64001]={64002:1.0,64003:1.0,64004:1.0,}temp[64002]={64001:1.0,64003:1.0,64004:1.0,}期待的结果:64001{64002:1.0,6......
  • C#去掉字符串首尾字符
    以下是多种不同的实现方法来去除C#字符串的首尾字符:1、使用Substring方法:stringinput="HelloWorld!";stringoutput=input.Substring(1,input.Length-2);2、使用Remove方法:stringinput="HelloWorld!";stringoutput=input.Remove(0,1).Remove(input.Leng......
  • LeetCode 第8题:字符串转换整数 (atoi)
    本文我们来看看LeetCode第8题.字符串转换整数(atoi)的解析过程。文章目录一、引言题目描述示例二、解题思路1.丢弃无用的前导空格2.处理正负号3.读入数字4.处理整数溢出5.组合起来思路流程图三、Java代码实现代码解析1.移除前导空格2.处理正负号3.转换数......
  • 28. 找出字符串中第一个匹配项的下标
    28.找出字符串中第一个匹配项的下标ShowSwiftCodefunccomputePMT(_pattern:String)->[Int]{letm=pattern.lengthvarpmt=[Int](repeating:0,count:m)varj=0foriin1..<m{whilej>0&&pattern[p......
  • 2981. 找出出现至少三次的最长特殊子字符串 I
    题目描述给你一个仅由小写英文字母组成的字符串s。如果一个字符串仅由单一字符组成,那么它被称为特殊字符串。例如,字符串"abc"不是特殊字符串,而字符串"ddd"、"zz"和"f"是特殊字符串。返回在s中出现至少三次的最长特殊子字符串的长度,如果不存在出现至少三次的特......
  • Day 8 | 344.反转字符串 、541. 反转字符串II 、151.翻转字符串里的单词
    344.反转字符串建议:本题是字符串基础题目,就是考察reverse函数的实现,同时也明确一下平时刷题什么时候用库函数,什么时候不用库函数题目链接/文章讲解/视频讲解:https://programmercarl.com/0344.反转字符串.html思考太简单了classSolution:defreverseString(self,......
  • 17.js字符串
    字符串创建1.字面量创建    var字符串名=字符串2.内部构造函数创建    var字符串名=newString('字符串')length属性    只能读取不能设置varstr='abcdfegfgl'console.log(str.length)//10str.length=5......
  • C# String.Format 数值类型格式化字符串 保留两位小数
    统计学中普遍遵循四舍六入五成双例:32.6752-》32.67例:32.6755-》32.67注:String.Format() .framework4.7.2是四舍五入;.net6.net7则符合四舍六入五成双;其余版本没有进行测试。//.framework4.7.2varDistance=32675;vara=String.Format("{0:N2}",Distance/100......
  • 用python字典统计CSV数据
    1.用python字典统计CSV数据的步骤和代码示例为了使用Python字典来统计CSV数据,我们可以使用内置的csv模块来读取CSV文件,并使用字典来存储统计信息。以下是一个详细的步骤和完整的代码示例:1.1步骤(1)导入csv模块。(2)打开CSV文件并读取数据。(3)初始化一个空字典来存储统计信息。......