首页 > 解决方案 > 将输出存储到一个列表中

问题描述

这是我在此视频中讨论的问题的代码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

抱歉,如果问题令人困惑。我是一个菜鸟,简单的解决方案将不胜感激。:)

标签: pythonlist

解决方案


您必须将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

推荐阅读