python - 将输出存储到一个列表中
问题描述
这是我在此视频中讨论的问题的代码https://www.youtube.com/watch?v=XCeDBWI4sa4 我还没有完成编写最终代码,因为我卡在了中途。
a=list(map(int,input().strip().split())) # takes input as a list
for k in range(0,len(a)):
b=str(a[k]) #turns each element in the list a into a string
d=[int(c) for c in str(b)] #divides the digits of one element in the string b, for example, 456 will be divided into three different elements in the list as 4,5,6
d.sort() #sorts the list in ascending order
final=[]
e=d[0]*7+d[-1]*11 #multiplies smallest digit by 7 and largest by 11 and adds the results
f= list(map(int, str(e))) #turns e into a string, stores each digit as int into the list f
if len(f)>2: #removes the MSB from the list if number is bigger than 2 digits
del f[0]
strings = [str(x) for x in f] # turns the list into an integer and adds into the list final
a_string = "".join(strings)
an_integer = int(a_string)
final.append(an_integer)
else:
strings = [str(x) for x in f] # turns the list into an integer and adds into the list final
a_string = "".join(strings)
an_integer = int(a_string)
final.append(an_integer)
print(final)
我希望列表“最终”具有所有元素的位得分,但我的输出是不同的列表,如下所示:
234 567
[58]
[12]
我如何获得输出:
58 12
抱歉,如果问题令人困惑。我是一个菜鸟,简单的解决方案将不胜感激。:)
解决方案
您必须将final
列表放在for loop
. 如果你把它放在下面,它将在每次循环运行后重置。
final=[]
a=list(map(int,input().strip().split())) # takes input as a list
for k in range(0,len(a)):
b=str(a[k]) #turns each element in the list a into a string
d=[int(c) for c in str(b)] #divides the digits of one element in the string b, for example, 456 will be divided into three different elements in the list as 4,5,6
d.sort() #sorts the list in ascending order
推荐阅读
- fortran - 使用 OpenMP 并行化包含指针数组的可分配类型的英特尔 Fortran 代码
- docker - 在 docker 容器中以 root 身份被拒绝权限
- javascript - Discord bot,如何获得所有连接的“公会/服务器”
- php - 重启PHP-FPM时出现403错误如何解决?
- javascript - 对循环感到困惑 - 欢迎任何帮助
- html - 反应 + CSS 网格 + MongoDB?
- php - Codeigniter 查询不返回我选择的行
- visual-studio-code - 在 VSCode 中切换工作区,无需每次都重新加载
- c++ - 迭代期间添加到 std::unordered_set(或 unordered_map)中的元素是否会在迭代期间被访问?
- javascript - element.count & element.value 在数组中是什么意思?