[英]Create sorted list from dictionary of 2 keys and 2 tuples
试图创建一个函数,我可以使用它来创建两个键和两个元组作为值的排序列表。 我的“ for”循环在某处出现问题,由于某种原因,它将仅打印键和第一个元组。 不知何故,第二个元组永远不会通过排序器。
def printDictionary(dictionaryParm):
for x in dictionaryParm:
header = []
header.append(x)
for y in dictionaryParm.values():
value = list(y)
value.sort()
output = header + value
for item in output:
print item
dictionaryTest = dict()
dictionaryTest["Key 1"] = ("234","123","345")
dictionaryTest["Key 2"] = ("456","678","567")
printCourseDictionary(dictionaryTest)
我的猜测是,“ for y”语句在某处存在问题,但是经过几个版本(包括中断和其他内容)后,我仍然无法获得正确的输出。
理想情况下,输出应如下所示:
Key 1
123
234
345
Key 2
456
567
678
有什么想法吗?
您的代码有一些缩进问题,但如果我理解正确,则需要以下代码
def printDictionary(dictionaryParm):
for x in dictionaryParm:
header = [x]
value = list(dictionaryParm[x])
value.sort()
output = header + value
for item in output:
print(item)
dictionaryTest = dict()
dictionaryTest["Key 1"] = ("234","123","345")
dictionaryTest["Key 2"] = ("456","678","567")
printDictionary(dictionaryTest)
代码输出
Key 2
456
567
678
Key 1
123
234
345
问题是@缩进循环,在其中对值进行排序和添加。 这是您的问题吗? def printDictionary(dictionaryParm):
for k, y in dictionaryParm.items(): value = list(y) value.sort() output = ([k]+ value) for it in output: print (it)
dictionaryTest = dict() dictionaryTest["Key 1"] = ("234","123","345") dictionaryTest["Key 2"] = ("456","678","567") printDictionary(dictionaryTest)
Output code Key 1 123 234 345 Key 2 456 567 678
尝试这个
def printDictionary(dictionaryParm):
for x in dictionaryParm:
header = []
header.append(x)
#print header
value=list(dictionaryParm.get(x))
print value
output = header + value
for item in output:
print item
dictionaryTest = dict()
dictionaryTest["Key 1"] = ("123","234","345")
dictionaryTest["Key 2"] = ("456","567","678")
printDictionary(dictionaryTest)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.