最Python的解決方案是
start_list = [5, 3, 1, 2, 4]
square_list = [ i ** 2 for i in start_list ]
print(sorted(square_list))
或oneliner:
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
如果您打印square_list,會發生什麼情況? – 2015-02-23 20:55:43
你的意思是如果我刪除sort()命令並打印它?然後它只打印出4 – Liblikas 2015-02-23 20:58:02
準確!這是start_list中的最後一個值。看到mfitzp的答案是如何發生的。 – 2015-02-23 21:05:11