我創建了以下串列:
list_article = ['My pasta $500.0', 'coffee $100.0', 'Oat can $50.0']
現在我想提取數字,求和并回傳一個總數,如下所示:
Total = 650.0
我已經創建了一個將專案添加到串列的函式:
def add_item(item_name):
item_qty = input('\nEnter amount to donate: ')
item_qty_float = float(item_qty)
item_str = f'{item_name} cost ${item_qty_float}'
return item_str
user = ''
if user == '':
print('You are not authorized.')
else:
item_string = add_item(user)
list_article.append(item_string)
現在我想列印總數: Total = 650.0 有沒有辦法提取字串串列中的數字?
uj5u.com熱心網友回復:
嘗試一些正則運算式,像這樣。
from re import findall
findall(r"[0-9] \.[0-9] ", listItem)
https://regexr.com/6ifhn
uj5u.com熱心網友回復:
有一種方法可以提取數字,盡管創建字典會更容易。此外,您可以在定義的函式之外使用全域變數,這樣每次您使用函式時,它都會將它們的輸入添加到全域變數中,從而增加您的總數。如果你沒有被告知,字典就像一個串列,但它有一個鍵和值對。例如:
dictionary = {'My pasta': 500.0, 'coffee': 100.0, 'Oat can': 50.0} <-- dictionary
用逗號分隔的每個字典條目的格式是key: value. 為了訪問字典中鍵的值,請在括號內提及變數和鍵。例子:
dictionary = {'My pasta': 500.0, 'coffee': 100.0, 'Oat can': 50.0}
pasta_cost = dictionary['My pasta']
您可以在字典上使用三種方法來提取資料。"
dictionary.values() <-- Gives values in a list format
dictionary.items() <-- Gives both keys and values in a list format
dictionary.keys() <-- Gives keys in a list format
在您的情況下,您可能想要執行以下操作以添加值:
dictionary = {'My pasta': 500.0, 'coffee': 100.0, 'Oat can': 50.0}
total_cost = 0
for value in dictionary.values():
total_cost = value
print(total_cost)
輸出:650.0
如果您真的想從字串中提取數字,您可以為串列中的每個元素使用該.replace()方法取出任何按字母順序排列的內容(或空格)并將其替換為任何內容。
或者,您可以使用re模塊中的正則運算式在字串中查找數字,但您需要學習正則運算式的語法。
希望這可以幫助!
uj5u.com熱心網友回復:
在我看來,您的資料結構是錯誤的。
但是,如果任務必須通過您的邏輯解決,您可以撰寫
sum(float(s[s.rfind('$') 1:]) for s in list_article)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/452110.html
標籤:Python python-3.x 列表
上一篇:有條件地復制串列C#
