最pythonic的解决方案是
start_list = [5, 3, 1, 2, 4]
square_list = [ i ** 2 for i in start_list ]
print(sorted(square_list))
或单线:
print(sorted(i ** 2 for i in [5, 3, 1, 2, 4]))
让我们剖析您的代码:
# here you create an empty list and assign it to
# square list
square_list = []
# yet here you will assign each item of start_list
# to the name square list one by one
for square_list in start_list:
# then you square that number, but it is not stored anywhere
square_list ** 2
# at this point, square_list contains the last element
# of start_list, that is the integer number 4. It does
# not, understandably, have the `.sort` method.
print square_list.sort()
直接的解决方法是:
start_list = [ 5, 3, 1, 2, 4 ]
square_list = []
for element in start_list:
square_list.append(element ** 2)
square_list.sort() # note that printing this would say "None"
print square_list