簡體   English   中英

如何將序列中的字符串轉換為浮點數?

[英]How to turn strings in a sequence into a float?

我是Python的新手,我無法弄清楚。 這是我的代碼:

salesFile = input("Enter sales file name: ")
totalFiles = input("Enter name for total sales file: ")

salesFileOpen = open(salesFile, "r")
sales = salesFileOpen.readlines()

for line in sales:
    newLine = (line.strip().split(" "))

for number in newLine:
    totals = float(newLine[number]) + float(newLine[number])
print(newLine)
print(totals)

我輸入為salesFile的文件顯示為

['$1120.47', '$944.42']
['$72.29', '$588.23']
['$371.21', '$2183.84']

我需要在水平行中添加每個值,並為每行總計。 為此,我嘗試做

totals = float(newLine[number]) + float(newLine[number])

它返回作為錯誤說:

totals = float(newLine[number]) + float(newLine[number])
TypeError: list indices must be integers or slices, not str"

有任何想法嗎?

您會看到一個錯誤,因為在一個字符串列表上進行了迭代,因此number實際上是一個字符串,並且按字符串進行索引沒有任何意義。 無需索引。

更換

for number in newLine:
    totals = float(newLine[number]) + float(newLine[number])

有:

for number in newLine:
    totals = float(number[1:]) + float(number[1:])

將事物包裝在一起:

for i, line in enumerate(sales):
    newLine = (line.strip().split(" "))

    total = 0
    for number in newLine:
        total += float(number[1:]) 

    print 'Total for line # {} is: {}'.format(i + 1,  total)

暫無
暫無

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

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