You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何转换从文本文件读取的列表中的单位(Kbps转Mbps)

问题需求

已完成从文本文件读取数值并转换为float的步骤,现要求:

  • 不使用index()方法
  • 将列表中所有Kbps单位的数值转换为Mbps(如1200 Kbps转为1.2)
  • 最终得到列表[7, 1.2, 15, 32]
  • 不得修改原文本文件

现有代码

bw  = [] #another comment: create an empty list
with open("task4.txt") as file_name:
    for line in file_name:
        a = line.split() #The split() method splits a string into a list - whitspace as a default
        bw.append(a[0]) #only appending the first value
        floats = [float(line) for line in bw] #Turnes the string into a float

print(bw)

文本文件内容(task4.txt)

7 Mbps
1200 Kbps
15 Mbps
32 Mbps

解决方案

原代码只提取了数值部分,丢失了单位信息,无法判断是否需要转换。修改思路是同时读取数值和单位,根据单位决定是否做转换:

result = []
with open("task4.txt") as file:
    for line in file:
        # 拆分每行的数值和单位
        value_str, unit = line.strip().split()
        value = float(value_str)
        # 判断单位,Kbps转Mbps需除以1000
        if unit == "Kbps":
            result.append(value / 1000)
        else:
            result.append(value)

print(result)  # 输出: [7.0, 1.2, 15.0, 32.0]

说明

  1. 用line.strip().split()拆分每行,直接解构为数值字符串和单位,完全不需要index()方法
  2. 转换数值为float后,根据单位判断是否执行除以1000的转换
  3. 若需要将结果中的整数形式保留为int(如7而非7.0),可以在添加时做判断转换:int(value) if value.is_integer() else value

内容的提问来源于stack exchange,提问作者user21143475

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:25:39