簡體   English   中英

如何在python中打印列表項

[英]How to print list items in python

我寫了以下代碼:

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

我想做的是用變量名打印最大的數字,例如:

d:8
b:5
c:2

但是使用上面的代碼,我只能打印數字的升序列表,而不能打印相應的變量名。 請提出解決此問題的方法。

請改用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

我認為您可以使用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)

列表不保存變量名

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM