Python 3.x 使用for循环打印向后列表?
下面是我的代码,我按升序打印,现在我需要按降序打印,但不知道如何打印?我已经尝试了下面的代码,但是它没有打印我想要的结果,例如Jill,8,1,0Python 3.x 使用for循环打印向后列表?,python-3.x,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(sorte
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)
OP非常模糊,我无法确定提供的列表是如何“排序”的,而列表的反转会首先打印出“吉尔”。无论如何,我假设:
- 字符串应该是名称
- 后面的int是上述名称的属性
sorted_list = ["jack",4,3,1,"jill",8,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
nameDict = {}
tmp = None
for _ in sorted_list:
if isinstance(_, str):
tmp = _
nameDict[tmp] = []
else:
if tmp: nameDict[tmp].append(_)
final = []
for name in list(reversed(sorted(nameDict))):
final += [name] + nameDict[name]
print final
在写这篇文章的时候,OP似乎回应了我的评论,显然希望属性本身按降序排列
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
如果您需要名称的正确顺序,那可能会有点不同,因为dict是未排序的。这是怎么回事?我正在创建一个列表,并尝试附加不同的属性,以尝试按降序打印。我正在尝试,但是我的输出被搞得一团糟。这个列表“排序”是什么意思这只是一个可变名称谢谢!我需要一个for循环,虽然我的python非常有限,但里面有for循环。你说的“我有有限的python”是什么意思?我对DICTS一无所知。你问的问题不应该用简单的for循环来完成。在提出这样的问题之前,请先阅读python的基础知识。@Goodies我钦佩您的患者和在这方面的决心。你通常不应该容忍这种含糊不清的要求。。