簡體   English   中英

我想在Python中將字符串列表(溫度值:['23.14C','19 .91C'] ['54 .04F','32 .64F'])轉換為浮點數

[英]I want to convert a list of strings (temperature values: [ '23.14C', '19.91C'] ['54.04F', '32.64F']) into floats, in Python

我有華氏和攝氏兩個溫度列表,例如:( ['23,6C', '16,5C', '38,4C',...] ['19.6F', '72.3F', '81.75F', '18.02F' ['23,6C', '16,5C', '38,4C',...]['19.6F', '72.3F', '81.75F', '18.02F' ,)的數據類型為字符串,我想將它們轉換為浮點數,以便能夠將其計算為開爾文。 字母可以刪除。

我已經嘗試過使用for循環刪除字母,但是后來我成為了點或逗號前后每個值的字符串列表。 當我想直接轉換它們時,由於值后面的字母,它不起作用。

for pos in list_cel:
    for buchst in pos:
        if buchst == "C":
            buchst.replace("C", " ")
        else:
            nlist_cel.append(buchst)
print(nlist_cel)

#給我一個字符串列表,每個逗號后都分開

例如['23','6',...]而不是[23,6 or 23.6]

輸出應如下所示

[23.6, 16.5, 38.4,] 
[19.6, 72.3, 81.75,]

使用列表理解, 更多細節

str.replace(old,new) -返回字符串的副本,其中所有出現的子字符串old都替換為new

fahrenheit =['19.6F', '72.3F', '81.75F', '18.02F']

celsius = ['23,6C', '16,5C', '38,4C']

fahrenheit = [float(i.replace("F","")) for i in fahrenheit ]
celsius = [float(i.replace("C","").replace(",",".")) for i in celsius ]

print(fahrenheit)
print(celsius)

O / P:

[19.6, 72.3, 81.75, 18.02]
[23.6, 16.5, 38.4]

浮動轉換

for pos in list_cel:
for buchst in pos:
    if "C" in buchst:
       val = buchst.replace("C", " ")
       if ',' in val:
          nlist_cel.append( float (val.replace(",", ".")))
       else:
          nlist_cel.append(float(val))

 print(nlist_cel)

替換逗號以對單元進行點分割

lst=['23,6C', '16,5C', '38,4C',]
lst=[float(i[:-1].replace(',','.')) for i in lst]

產量

[23.6、16.5、38.4]

使用帶有列表理解str.replacestr.strip

例如:

data = (['23,6C', '16,5C', '38,4C'], ['19.6F', '72.3F', '81.75F', '18.02F'])
print([[float(j.replace(",", ".").rstrip("CF")) for j in i] for i in data])

輸出:

[[23.6, 16.5, 38.4], [19.6, 72.3, 81.75, 18.02]]

嘗試這個 -

for value in raw_list_value:
    if ',' in value:
        new_val = float('.'.join(i[:-1].split(','))
    else:
        new_val = float(value[:-1])
    temp_list.append(new_value)
list_cel = ['23,6C', '16,5C', '38,4C']
list_far = ['19.6F', '72.3F', '81.75F', '18.02F']


list_cel_float = map(lambda x:float(x.replace(',','.').replace('C','')), list_cel)
list_far_float = map(lambda x:float(x.replace(',','.').replace('F','')), list_far)

print list_cel_float
print list_far_float

如果您知道所有臨時字母都附加了“ F”或“ C”,那么這是一個快速解決方案:

fah = ['19.6F', '72.3F', '81.75F', '18.02F']
cel = ['23,6C', '16,5C', '38,4C']

如果只是檢查列表中的第一個元素以查看是否存在“ F”或“ C”,並相應地進行操作以返回列表。 也消除了逗號,以后不必處理它們會容易得多。

def f_or_c_temp(temp_list):
    if 'F' in temp_list[0]:
        return [temp.replace('F','') for temp in f]
    if 'C' in temp_list[0]:
        c = [temp.replace('C','') for temp in temp_list]
        return [temp.replace(',','.') for temp in c]

因此對於華氏溫度

f_or_c_temps(fah)

輸出:

['19.6', '72.3', '81.75', '18.02']

對於賽爾修斯

f_or_c_temps(cel)

輸出:

['23.6', '16.5', '38.4']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM