python - 如果一个变量有两种可能的结果,你如何分别从列表中添加值

标签 python list python-3.x sum

这个赋值调用另一个函数:

def getPoints(n):
    n = (n-1) % 13 + 1
    if n == 1:
        return [1] + [11]
    if 2 <= n <= 10:
        return [n]
    if 11 <= n <= 13:
        return [10] 

因此,我的作业要求我将 52 个数字列表中数字的所有可能点的总和相加。到目前为止,这是我的代码。

def getPointTotal(aList):
    points = []
    for i in aList:
        points += getPoints(i)
        total = sum(points)   
    return aList, points, total

但是问题是整数 1 有两个可能的点值,1 或 11。当我对点求和时,它会正确地做所有事情,但它会将 1 和 11 加在一起,而我需要它来计算总和,如果整数为1,如果整数为11。

例如:

>>>getPointTotal([1,26, 12]) # 10-13 are worth 10 points( and every 13th number that equates to 10-13 using n % 13.
>>>[21,31] # 21 if the value is 1, 31 if the value is 11.

另一个例子:

>>>getPointTotal([1,14]) # 14 is just 14 % 13 = 1 so, 1 and 1.
>>>[2, 12, 22] # 1+1=2, 1+11=12, 11+11=22

我的输出是:

>>>getPointTotal([1,14])
>>>[24] #It's adding all of the numbers 1+1+11+11 = 24.

所以我的问题是,如何让它将值 1 与值 11 分开添加,反之亦然。这样一来,当我确实有 1 时,它会添加所有值和 1,或者它会添加所有值和 11。

最佳答案

您在存储从 getPoints() 返回的所有值时犯了一个错误。您应该只存储到目前为止返回的点数的可能总数。您可以将所有这些存储在一个集合中,并使用 getPoints() 返回的所有可能值更新它们。一套会自动去掉重复的分数,比如1+11和11+1。您可以在最后将集合更改为排序列表。这是我的代码:

def getPointTotal(aList):
    totals = {0}
    for i in aList:
        totals = {p + t for p in getPoints(i) for t in totals}
    return sorted(list(totals))

我得到这些结果:

>>> print(getPointTotal([1,26, 12]))
[21, 31]
>>> print(getPointTotal([1,14]))
[2, 12, 22]

关于python - 如果一个变量有两种可能的结果,你如何分别从列表中添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39938449/

相关文章:

python - 将 2 列类似计数器的 csv 文件转换为 Python collections.Counter?

python - 集中两个列表交替python

python - 如何从该输入字符串中提取数字

python - scikit-learn:为什么这个 2 折交叉验证图看起来像 4 折交叉验证?

python - 我需要在 mongodb 中关闭连接吗?

python - 如何附加到深度嵌套在字典中的列表并保留嵌套结构?

python - 为什么我要使用 `async def` 而不是 `@asyncio.coroutine`?

python - 是否可以根据 Python 中的密码安全地加密然后解密数据?

Python与C交互——回调函数

Python-fu 脚本未显示在 Gimp 菜单中