首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python,带“def”和“for-循环”的指数子

python,带“def”和“for-循环”的指数子
EN

Stack Overflow用户
提问于 2021-12-23 04:48:16
回答 4查看 57关注 0票数 0

输入:

代码语言:javascript
复制
numbers = [1,2,3]
increment = 5

预期输出:

代码语言:javascript
复制
[1, 32, 243]

结果与我的代码:

代码语言:javascript
复制
1
32
243

代码:

代码语言:javascript
复制
def power(x, y):

    if (y == 0): return 1
    elif (int(y % 2) == 0):
        return (power(x, int(y / 2)) *
            power(x, int(y / 2)))
    else:
        return (x * power(x, int(y / 2)) *
                power(x, int(y / 2)))

for number in numbers:
    exponentiation = power(number,increment)
    print(exponentiation)

我试图在没有pow()和'**‘函数的列表中找到数字的平方根。我已经找到了每个数字的平方根,但我想知道如何把它们放在列表中。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2021-12-23 04:51:06

您正在打印指数,但您想要输出列表。这就是你想要做的:

代码语言:javascript
复制
# your function code above

answer = []
for number in numbers:
    exponentiation = power(number,increment)
    answer.append(exponentiation)

print(answer)

这将使:

代码语言:javascript
复制
[1, 32, 243]
票数 1
EN

Stack Overflow用户

发布于 2021-12-23 04:53:46

您应该在for-循环之前创建一个空列表,然后在for-循环中创建一个空列表,而不是打印每个数字,而是将其附加到列表中。最后,打印清单。

代码语言:javascript
复制
def power(x, y):

    if (y == 0): return 1
    elif (int(y % 2) == 0):
        return (power(x, int(y / 2)) *
            power(x, int(y / 2)))
    else:
        return (x * power(x, int(y / 2)) *
                power(x, int(y / 2)))

output_list = []

for number in numbers:
    exponentiation = power(number,increment)
    output_list.append(exponentiation)

print(output_list)
票数 1
EN

Stack Overflow用户

发布于 2021-12-23 04:51:49

你可以用单行表示循环-

代码语言:javascript
复制
exponentiation = [power(number,increment) for number in numbers]
print(exponentiation)
#[1,32,243]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70457756

复制
相关文章

相似问题

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