【问题标题】:How do I print out different variables in the "for" loop in different order python如何以不同的顺序在“for”循环中打印出不同的变量python
【发布时间】:2020-08-29 08:04:42
【问题描述】:

所以这是代码,我想以不同的顺序从字典中打印出变量我该怎么做?

    phonebook = {}

    line = input('Name and clour: ')
    while line:
     name, color = line.split()
     phonebook[name] = color 
     line = input('Name and clour: ')
    for x, y in phonebook.items():
    print(x, y) 

【问题讨论】:

  • 不同的顺序是什么意思?

标签: python string dictionary


【解决方案1】:

请注意,字典不是按插入顺序排序的,因为它是implemented as a hash table。如果您仍然想打乱它的顺序,您可以将其键转换为一个列表,然后打乱它 - 您将无法将它用作字典,因为顺序将被恢复:

import random
keys =  list(phonebook.keys())
random.shuffle(keys)
new_phonebook_list_of_tuples = [(key, phonebook[key]) for key in keys]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 2021-12-03
  • 2020-10-14
相关资源
最近更新 更多