首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问字典中列表中的全部值,而不是单个字符?

如何访问字典中列表中的全部值,而不是单个字符?
EN

Stack Overflow用户
提问于 2022-03-07 01:52:41
回答 1查看 53关注 0票数 -1

我对编码非常陌生,我已经试着查找并重新阅读我的笔记,但我想不出这一条。我试图检索字典(all_customers)中列表中的单个值。当我试图检索一个数字时的例子:

代码语言:javascript
复制
print(f"Earnings from how many months they subscribed for = ${(all_customers['customer1'][0])}")

但是,在索引时,它检索单个字符(如上面的示例所示,它返回括号:[),而不是完整的数字(如151)。这应该更像:如果我为第一个客户输入25 for months_subscribed10 for ad_free_months5 for videos_on_demand_purchases,那么all_customers['customer1']应该返回[151, 20, 139.95],而上面我试图打印的示例应该是“他们订阅=$151的月的收益”,而不是“他们订阅= [”订阅了多少个月的收益。

代码语言:javascript
复制
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}"

我希望这是一个可以问的问题!对不起,我对这件事很陌生:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-07 02:03:29

尝试打印出all_customers字典,您将看到问题所在:

代码语言:javascript
复制
>>> all_customers
{'customer1': '[32, 8, 83.97]', 'customer2': '[25, 6, 55.98]', 'customer3': '[18.0, 4, 27.99]'}

你所有的列表实际上都是字符串。因为这句话:

代码语言:javascript
复制
all_customers[f"customer{i+1}"] = f"{indi_sub_sum}"

您要给它分配一个字符串,而不是列表。改为:

代码语言:javascript
复制
all_customers[f"customer{i+1}"] = indi_sub_sum

应该为你解决这个问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71375678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档