简体   繁体   English

如何在python中打印列表项

[英]How to print list items in python

I have written the following code: 我写了以下代码:

def count():
    a = 1
    b = 5
    c = 2
    d = 8
    i = 0
    list1 = [a, b, c, d]
    le = len(list1)

    while (i < le):
        x = max(list1)
        print(x)
        list1.remove(x)
        i = i + 1

What I want to do is to print the largest number with its variable name like: 我想做的是用变量名打印最大的数字,例如:

d:8
b:5
c:2

but using the above code I can only print the ascending list of numbers, not the corresponding variable names. 但是使用上面的代码,我只能打印数字的升序列表,而不能打印相应的变量名。 Please suggest a way to fix this. 请提出解决此问题的方法。

Use a dict instead: 请改用dict

In [2]: dic=dict(a=1, b=5, c=2, d=8)

In [3]: dic
Out[3]: {'a': 1, 'b': 5, 'c': 2, 'd': 8}

In [5]: sortedKeys=sorted(dic, key=dic.get, reverse=True)

In [6]: sortedKeys
Out[6]: ['d', 'b', 'c', 'a']

In [7]: for i in sortedKeys:
   ...:     print i, dic[i]
   ...:     
d 8
b 5
c 2
a 1

I think you can use OrderedDict() 我认为您可以使用OrderedDict()

from collections import OrderedDict

a, b, c, d = 1, 2, 3, 6
vars = {
     'a' : a,
     'b' : b,
     'c' : c,
     'd' : d
}

d_sorted_by_value = OrderedDict(sorted(vars.items(), key=x.get, reverse=True))

for k, v in d_sorted_by_value.items():
    print "{}: {}".format(k,v)

List don't save variable names 列表不保存变量名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM