我是編碼新手,我嘗試查找并重新閱讀我的筆記,但我無法弄清楚這一點。我正在嘗試檢索字典 ( all_customers) 內串列中的各個值。我嘗試檢索數字時的示例:
print(f"Earnings from how many months they subscribed for = ${(all_customers['customer1'][0])}")
但是在索引時,它會檢索單個字符(如上面的示例中它回傳括號:)[,而不是完整的數字(如151)。它應該更像:如果我為第一個客戶輸入25for months_subscribed、10forad_free_months和5for ,則應該回傳,并且我嘗試在上面列印的示例應為“他們訂閱了多少個月的收入 = 151 美元”而不是“收入”他們訂閱了多少個月= [“。videos_on_demand_purchasesall_customers['customer1'][151, 20, 139.95]
def subscription_summary(months_subscribed, ad_free_months, video_on_demand_purchases):
#price based on months subscribed
if int(months_subscribed) % 3 == 0:
months_subscribed_price = int(months_subscribed)/3*18
elif int(months_subscribed) > 3:
months_subscribed_price = int(months_subscribed)%3*7 int(months_subscribed)//3*18
else:
months_subscribed_price = int(months_subscribed)*7
#price of ad free months
ad_free_price = int(ad_free_months)*2
#price of on demand purchases
video_on_demand_purchases_price = int(video_on_demand_purchases)*27.99
customer_earnings = [months_subscribed_price, ad_free_price, video_on_demand_purchases_price]
return customer_earnings
#Loop through subscription summary 3 times, to return 3 lists of customers earnings and add them to a dictionary
all_customers={}
for i in range(3):
months_subscribed = input("How many months would you like to purchase?: ")
ad_free_months = input("How many ad-free months would you like to purchase?: ")
video_on_demand_purchases = input("How many videos on Demand would you like to purchase?: ")
#congregate individual customer info into list and run it through the function
customer = [months_subscribed, ad_free_months, video_on_demand_purchases]
indi_sub_sum = subscription_summary(customer[0], customer[1], customer[2])
#congregate individual customers subscription summary lists into a dictionary
all_customers[f"customer{i 1}"] = f"{indi_sub_sum}"
我希望這是一個可以問的問題!對不起,我是新手:)
uj5u.com熱心網友回復:
試著列印出all_customers字典,你會發現問題出在哪里:
>>> all_customers
{'customer1': '[32, 8, 83.97]', 'customer2': '[25, 6, 55.98]', 'customer3': '[18.0, 4, 27.99]'}
您所有的串列實際上都是字串。那是因為這條線:
all_customers[f"customer{i 1}"] = f"{indi_sub_sum}"
您正在為其分配一個字串而不是串列。將其更改為:
all_customers[f"customer{i 1}"] = indi_sub_sum
應該為你解決。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439691.html
下一篇:遞回型別和串列有什么區別?
