我对编码非常陌生,我已经试着查找并重新阅读我的笔记,但我想不出这一条。我试图检索字典(all_customers)中列表中的单个值。当我试图检索一个数字时的例子:
print(f"Earnings from how many months they subscribed for = ${(all_customers['customer1'][0])}")但是,在索引时,它检索单个字符(如上面的示例所示,它返回括号:[),而不是完整的数字(如151)。这应该更像:如果我为第一个客户输入25 for months_subscribed、10 for ad_free_months和5 for videos_on_demand_purchases,那么all_customers['customer1']应该返回[151, 20, 139.95],而上面我试图打印的示例应该是“他们订阅=$151的月的收益”,而不是“他们订阅= [”订阅了多少个月的收益。
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}"我希望这是一个可以问的问题!对不起,我对这件事很陌生:)
发布于 2022-03-07 02:03:29
尝试打印出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://stackoverflow.com/questions/71375678
复制相似问题