gpt4 book ai didi

python - 在Python中反转数字列表的数字

转载 作者:行者123 更新时间:2023-12-02 18:15:03 28 4
gpt4 key购买 nike

for i in range(len(primo)):
reversed_num = 0
while i > 0:
digit = i % 10
reversed_num = reversed_num * 10 + digit
i //= 10
reversed.append (reversed_num)

for r in range(len(reversed)):
print (r)

我正在编写一个程序来反转列表中的一系列数字。例如:

输入:1234,124,654

输出:4321,421,456

该脚本对于一个数字可以正常工作,但对于一个列表则无法正常工作。

编辑:......................................

这是完整的工作代码。

#program to find the multiple of the first number that summed to its reverse creates a number divisible for the second number chosen. Results are shown up to five digits.

import sys

def main():
x = 0
y = 0
k = 0
z = 0
print ("Hello! Let's compare some numbers!\nPress input to continue")
input()
print ("Insert the first number")
x = input()
print ("Insert the second number")
y = input()
print()

primo = []
secondo = []

#list multiples

while k < 99999:
k = int(k) + int(x)
print (k)
primo.append (k)

while z < 99999:
z = int(z) + int(y)
print(z)
secondo.append (z)

print("The numbers have been calculated! Press to proceed")

input()

print("LOADING...")

#reverse all numbers of the first list

def myReverser(n: float) -> float:
return float(''.join(list(reversed(str(n)))))

reversedList = [myReverser(i) for i in primo]
reversedList = [int(i) for i in reversedList]

#sum the multiple of the first number and its reversed and search common values in res and secondo

res = [
x
for x, y in zip(primo, reversedList)
if (x + y) in secondo
]

print()
print()

if len(res) == 0:
print ("No results found")
else:
print ("The numbers are: ", res)

#ending

print ()
print ("Thank you for using my program!")
print ()
choice = input ("Would you try with another number? [Y/N] ").capitalize()

if choice == "Y":
main()
if choice == "N":
sys.exit()

main()

#no copyright intended. This code is open-source. Feel free to use it in other projects.

该脚本可以比较两个给定的数字,以找到第一个数字的倍数,将其倒数相加,创建一个可被所选的第二个数字整除的数字。结果最多显示五位数字。

最佳答案

不错的尝试,但是反转数字的函数怎么样?您应该很高兴知道 Python 中已经存在 reversed ,并且您可以这样使用它:

>>> list(reversed(str(0.1223142131)))
['1', '3', '1', '2', '4', '1', '3', '2', '2', '1', '.', '0']
>>> float(''.join(reversed(str(0.1223142131))))
1312413221.0

这样你就可以实现自己的功能:

def myReverser(n: float) -> float:
return float(''.join(reversed(str(n))))

然后在整个列表上使用它:

reversedList = [myReverser(i) for i in [1234, 124, 654]]

如果您不希望所有数字末尾有.0,则意味着您不需要 float ,而是integers,所以你可以这样做:

reversedList = [int(i) for i in reversedList]

关于python - 在Python中反转数字列表的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71707241/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com