0

我想从我的代码只能将列表中的数字相乘的范围内获得一个提供特定要求 的列表。我想在列表中乘以数字的“数字平方”

例如:定义的范围 = (1,200)

Wanted_list =[1^2,2^2,3^2,...,(34 = 3^2 * 4^2),(35 = 3^2 * 5^2),...,(199 = 1^2 * 9^2 * 9^2)]

这是我的代码

def mult(liste):
    a=1
    for i in liste:
        a*=i       #I think the problem is here
    return a

listemm = [x for x in range(1,200)]
print(listemm)
qe= [mult(int(digit) for digit in str(numb)) for numb in listemm]
print(qe)
4

2 回答 2

3

我会这样做:

r = range(1, 200)


def reduce_prod(n):
    p = 1
    for i in str(n):
        p *= int(i)**2
    return p


wanted_list = [reduce_prod(x) for x in r]

产生:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, ...]
#                                 ^
#                                 from 10 -> 1^2 * 0^2 = 0
于 2018-10-29T15:56:20.567 回答
1

你非常亲近。这是您自己尝试的最大范围为 30 的更正版本。问题是您的函数仅适用于两位数。在这里,我使用 if-else 条件来检查数字是否小于 10。如果是,我只需将其平方,否则将其发送到您的函数。

在函数中,您没有对数字进行平方。你也不需要listemm. 您可以直接range在列表理解中使用。

def mult(liste):
    a=1
    for i in liste:
        a*=i**2       # Square here (the problem was partly here)
    return a

qe= [numb**2 if numb<10 else mult(int(digit) for digit in str(numb)) for numb in range(1,30)]
print(qe)

# [1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
于 2018-10-29T15:55:21.430 回答