下面是我的代码我按升序打印这个我现在需要按降序打印但不知道如何?我已经尝试了下面的代码,但是它没有打印我想要的结果,即Jill,8,1,0第一次,很快
sorted_list = ["jack",4,3,1,"jill",8,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(len(sorted_list),2,-3,-1):
des_list.append(sorted_list[i-2])
des_list.append(sorted_list[i - 1])
des_list.append(sorted_list[i])
des_list.append(sorted_list[i+1])
print(des_list)
答案 0 :(得分:3)
有了这个,我创建了一个包含名称和属性的字典。这将按字母顺序排序,并按原始顺序排列属性。
sorted_list = ["jack",4,3,1,"jill",8,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
nameDict = {} # empty dictionary {key1 : value1, key2 : value2 } etc...
tmp = None # temporary variable used to keep track of the name
for _ in sorted_list:
if isinstance(_, str): # if the name is a string...
tmp = _ # ... set the temporary variable to the name
nameDict[tmp] = [] # create an entry in the dictionary where the value is an empty list. Example: { "jill" : [] }
else:
if tmp: nameDict[tmp].append(_) # as long as tmp is not None, append the value to it. For example, after we hit "jill", it will append 8 then 1 then 0.
final = [] # empty list to print out
for name in nameDict: # loop through the keys in nameDict
final += [name] + sorted(nameDict[name], reverse=True) # append the name to the final list as well as the sorted (descending) list in the dictionary
print final
在写这篇文章时,OP似乎已经回复了我的评论,并且显然希望属性本身按降序排列。
{{1}}
如果您需要正确顺序的名称,那可能会有所不同,因为dicts未排序。