使用for循环打印后退列表?

时间:2016-02-09 17:50:35

标签: python-3.x

下面是我的代码我按升序打印这个我现在需要按降序打印但不知道如何?我已经尝试了下面的代码,但是它没有打印我想要的结果,即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)

1 个答案:

答案 0 :(得分:3)

OP非常模糊,我无法确定列表提供的任何方式是“排序”,而列表的反转将首先打印出'jill'。无论如何,我假设:

  • 字符串应该是名称
  • 以下内容是上述名称的属性

有了这个,我创建了一个包含名称和属性的字典。这将按字母顺序排序,并按原始顺序排列属性。

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未排序。

相关问题