python-3.x 如何更改从文本文件读取的列表的单位?

sc4hvdpw  于 2023-02-06  发布在  Python
关注(0)|答案(3)|浏览(116)

我正在尝试更改文本文件中的值的单位,任务的第一部分是将字符串列表转换为浮点数,但现在(不使用index())我想将元素的单位从kbps更改为mbps,因此1200的值为1.2。
下面是将列表的值转换为浮点型的代码:

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)

文本文件如下所示:

7 Mbps
1200 Kbps
15 Mbps
32 Mbps

我需要的列表成为7,1.2,15,32没有改变文本文件,也没有使用索引。我想要一个程序,找到所有的kbps值,并把它们变成mbps

tgabmvqs

tgabmvqs1#

您必须检查单位的第一个字母,以确定是否除以1000将Kpbs转换为Mbps。

bw  = [] #another comment: create an empty list
with open("task4.txt") as file_name:
    for line in file_name:
        speed, unit = line.split()
        speed = float(speed)
        if unit.startswith('K'):
            speed /= 1000
        bw.append(speed)
print(bw)
juzqafwq

juzqafwq2#

如果你想在列表中的Mbps和Kbps,你可以试试我的代码如下:

with open('task4.txt', 'r') as file:
    sizes = []
    for line in file:
        size, unit = line.strip().split()
        if unit == 'Mbps':
            sizes.append(float(size))
        else:
            sizes.append(float(size)/1000)

print(sizes)
q1qsirdb

q1qsirdb3#

首先,您可以打开文件并将其解析为list,方法是:

speeds = []
with open("task4.txt", "r", encoding="utf-8") as file:
    speeds = file.read().splitlines()

阅读文件后,任务变为一行程序。

speeds = [str(int(x.split()[0]) / 1000) + " " + x.split()[1] if "kbps" in x.lower() else x for x in speeds]

为了便于阅读,我在这里提供了一个更详细的解决方案和注解,尽管它做的事情与上面的完全相同:

# Create a temporary array to hold the converted speeds
new_speeds = []
# For each speed in the list
for speed in speeds:
    # If the speed is in Kbps
    if "kbps" in speed.lower():
        # Fetch the raw speed integer and the unit name from the string
        n_kbps, unit = speed.split()
        # Convert the raw speed integer to Mbps
        n_kbps /= 100
        # Add the converted speed to the new_speeds array
        new_speeds.append(f"{n_kbps} {unit}")
    # If the speed is not in Kbps
    else:
        # Simply add the existing speed to the new_speeds array
        new_speeds.append(speed)
# Set the original speeds array to the resulting array
speeds = new_speeds

相关问题