【问题标题】:Sum up values at corresponding indices from another list总结另一个列表中相应索引处的值
【发布时间】:2014-02-20 05:49:36
【问题描述】:

我有 2 个列表,fantasiesdamages,每个长度为 19:

fantasies[0] = ("Extreme sports")
damages[0] = 250000
fantasies[1] = "Truffles"
damages[1] = 5000
....
fantasies[19] = "Coffee"
damages[19] = 50000

我的程序随机选择n幻想并打印选定的值:

import random
i = 0
while i<n:
    print (random.choice(fantasies))
    i = i + 1

现在我需要它来总计 damages 值,这些值对应于随机选择的 fantasies 值。

例如,如果程序在索引 2、6 和 18 处随机选择 fantasies,我需要它对相同索引处的 damages 求和。我该怎么做?

【问题讨论】:

    标签: python-3.x random


    【解决方案1】:

    您可以将zip它们成元组并汇总相关值:

    import random
    n = 3
    data = zip(fantasies, damages)
    total = 0
    for i in range(n):
        myChoice = random.choice(data)
        print myChoice[0]
        total += myChoice[1]
    

    我应该补充几点:

    1. 将来您可能希望使用字典来存储关联值,而不是拥有两个列表。

    2. 我感觉您需要独特的选择。如果是这样,您将需要使用shuffle

    【讨论】:

    • 我不确定这是否会导致问题,但是当用户调用该函数时,他们必须输入一个数量 n,以告诉程序要选择多少东西 ----- - trust_fund_monthly(n): """会让你拥有你最喜欢的 n 种花钱方式。"""
    • @user3331266 不明白为什么会有问题。
    猜你喜欢
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多