簡體   English   中英

如何檢查 python 中字符串列表中的數字?

[英]How to check for digit in list of string in python?

我創建了以下列表:

list_article = ['My pasta $500.0', 'coffee $100.0', 'Oat can $50.0']

現在我想提取數字,求和並返回總計,如下所示:

Total = 650.0

我已經創建了一個 function 來將項目添加到列表中:

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 有沒有辦法提取字符串列表中的數字?

有一種方法可以提取數字,盡管創建字典會更容易。 此外,您可以在定義的 function 之外使用全局變量,這樣每次您使用 function 時,它都會將其輸入添加到全局變量中,從而加起來就是您的總數。 如果您不知道,字典就像一個列表,但它有一個鍵值對。 例如:

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模塊中的正則表達式來查找字符串中的數字,但您需要學習正則表達式的語法。

希望這可以幫助!

我認為您的數據結構是錯誤的。

但是如果任務必須按照你的邏輯來解決,你可以寫

sum(float(s[s.rfind('$')+1:]) for s in list_article)

嘗試一些正則表達式,就像這樣。

from re import findall
findall(r"[0-9]+\.[0-9]+", listItem)

https://regexr.com/6ifhn

暫無
暫無

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

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