如何从数字/数字列表中获取整数?

发布于 2025-02-10 07:39:53 字数 135 浏览 0 评论 0原文

例如,说你有 [5,6] 输出应该是56

我能想到的唯一方法是将每个数字乘以其位置值,然后添加。 像这样的5 x 10 + 6 x 1 = 56

是否有更简单的方法?我想我可以转换为字符串,但是我不想使用字符串。还有其他选择吗?

for example lets say you have
[5,6]
the output should be 56

the only method I can think of is to multiply each digit by its place value and then add it.
like this 5 x 10 + 6 x 1 = 56

Is there a simpler way of doing this? I guess I can convert to string, but I dont want to use string. Any other alternatives?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

铜锣湾横着走 2025-02-17 07:39:53

我猜只是将相应的数字乘以1、10、100等是最简单的。但是您可以以一种很酷的方式进行。

L = [4, 2, 0, 6, 9]
num = sum([10**(len(L)-i-1)*L[i] for i in range(len(L))])

I guess just multiplying corresponding digits by 1, 10, 100 etc. is the simplest. But you can do this in a cool way.

L = [4, 2, 0, 6, 9]
num = sum([10**(len(L)-i-1)*L[i] for i in range(len(L))])
玩心态 2025-02-17 07:39:53
def my_function(my_list):
    final = ""
    for i in my_list:
        final = final + str(i)
    return int(final)

integer = my_function([5, 6])  # My function will output 56
def my_function(my_list):
    final = ""
    for i in my_list:
        final = final + str(i)
    return int(final)

integer = my_function([5, 6])  # My function will output 56
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文