在 Python 中随机改组字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19895028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Randomly shuffling a dictionary in Python
提问by MikhailTal
Well, the thing is, I had the need to use dictionaries in python, but I realized i couldn't randomly shuffle them. I have to randomly shuffle it, and assign the values to the same dictionary. Any help would be appreciated.
好吧,问题是,我需要在 python 中使用字典,但我意识到我不能随机洗牌。我必须随机洗牌,并将值分配给同一个字典。任何帮助,将不胜感激。
import random
i = 1
name = ""
helper = []
number_of_com = 0
win_0 = []
win_1 = []
win_2 = []
win_3 = []
win_4 = []
win_5 = []
win_6 = []
win_7 = []
win_8 = []
win_9 = []
win_10 = []
print ("Welcome to the Swiss Round Calculator. This project was made by Enes Kristo")
number_of_com = int(input("Please enter the number of the competitors:\n"))
if number_of_com <= 16:
loop = 3
elif number_of_com <= 32:
loop = 4
elif number_of_com <= 64:
loop = 5
elif number_of_com <= 128:
loop = 6
elif number_of_com <= 256:
loop = 7
elif number_of_com <= 512:
loop = 8
elif number_of_com <= 1024:
loop = 9
else:
loop = 10
while i <= number_of_com:
name = str(input("Name of competitor nr."+str(i)+":\n"))
helper.append([name, 0, 0])
i += 1
def odd():
b = 0
while b <= (number_of_com - 2):
helper_1 = helper[b]
b += 1
helper_2 = helper[b]
print ("Player " + str(helper_1[0]) + " is vs player " + str(helper_2[0]) + ".")
b += 1
helper_3 = helper[(number_of_com-1)]
print (str(helper_3[0])+" gets a free win.")
helper_3[1] += 1
helper[(number_of_com-1)] = helper_3
b = 0
while b <= (number_of_com - 2):
helper_1 = helper[b]
b += 1
helper_2 = helper[b]
print("In the match between player " + str(helper_1[0]) + " and player " +str(helper_2[0]) + " who won?")
a = int(input("Enter 1 if player " + str(helper_1[0]) + " won or 2 if player " + str(helper_2[0]) + " won.\n"))
if a == 1 or a == 2:
if a == 1:
helper_1[1] += 1
helper_2[2] += 1
b -= 1
helper[b] = helper_1
b += 1
helper[b] = helper_2
else:
helper_1[2] += 1
helper_2[1] += 1
b -= 1
helper[b] = helper_1
b += 1
helper[b] = helper_2
else:
print("Enter a correct number.")
b -= 1
continue
b += 1
random.shuffle(helper)
v = 0
while v < number_of_com:
helper_1 = helper[v]
if helper_1[1] == 0:
win_0.append(helper_1)
elif helper_1[1] == 1:
win_1.append(helper_1)
elif helper_1[1] == 2:
win_2.append(helper_1)
elif helper_1[1] == 3:
win_3.append(helper_1)
elif helper_1[1] == 4:
win_4.append(helper_1)
elif helper_1[1] == 5:
win_5.append(helper_1)
elif helper_1[1] == 6:
win_6.append(helper_1)
elif helper_1[1] == 7:
win_7.append(helper_1)
elif helper_1[1] == 8:
win_8.append(helper_1)
elif helper_1[1] == 9:
win_9.append(helper_1)
elif helper_1[1] == 10:
win_10.append(helper_1)
v += 1
random.shuffle(win_0)
random.shuffle(win_1)
random.shuffle(win_2)
random.shuffle(win_3)
random.shuffle(win_4)
random.shuffle(win_5)
random.shuffle(win_6)
random.shuffle(win_7)
random.shuffle(win_8)
random.shuffle(win_9)
random.shuffle(win_10)
while len(helper) > 0:
helper.pop()
helper.append(win_10)
helper.append(win_9)
helper.append(win_8)
helper.append(win_7)
helper.append(win_6)
helper.append(win_5)
helper.append(win_4)
helper.append(win_3)
helper.append(win_2)
helper.append(win_1)
helper.append(win_0)
def even():
b = 0
while b <= (number_of_com - 2):
helper_1 = helper[b]
b += 1
helper_2 = helper[b]
print ("Player " + str(helper_1[0]) + " is vs player " +str(helper_2[0]) + ".")
b += 1
b = 0
while b <= (number_of_com - 2):
helper_1 = helper[b]
b += 1
helper_2 = helper[b]
print("In the match between player " + str(helper_1[0]) + " and player " +str(helper_2[0]) + " who won?")
a = int(input("Enter 1 if player " + str(helper_1[0]) + " won or 2 if player " + str(helper_2[0]) + " won."))
if a == 1 or a == 2:
if a == 1:
helper_1[1] += 1
helper_2[2] += 1
b -= 1
helper[b] = helper_1
b += 1
helper[b] = helper_2
else:
helper_1[2] += 1
helper_2[1] += 1
b -= 1
helper[b] = helper_1
b += 1
helper[b] = helper_2
else:
print("Enter a correct number.")
b -= 1
continue
b += 1
random.shuffle(helper)
v = 0
while v < number_of_com:
helper_1 = helper[v]
if helper_1[1] == 0:
win_0.append(helper_1)
elif helper_1[1] == 1:
win_1.append(helper_1)
elif helper_1[1] == 2:
win_2.append(helper_1)
elif helper_1[1] == 3:
win_3.append(helper_1)
elif helper_1[1] == 4:
win_4.append(helper_1)
elif helper_1[1] == 5:
win_5.append(helper_1)
elif helper_1[1] == 6:
win_6.append(helper_1)
elif helper_1[1] == 7:
win_7.append(helper_1)
elif helper_1[1] == 8:
win_8.append(helper_1)
elif helper_1[1] == 9:
win_9.append(helper_1)
elif helper_1[1] == 10:
win_10.append(helper_1)
v += 1
random.shuffle(win_0)
random.shuffle(win_1)
random.shuffle(win_2)
random.shuffle(win_3)
random.shuffle(win_4)
random.shuffle(win_5)
random.shuffle(win_6)
random.shuffle(win_7)
random.shuffle(win_8)
random.shuffle(win_9)
random.shuffle(win_10)
while len(helper) > 0:
helper.pop()
helper.append(win_10)
helper.append(win_9)
helper.append(win_8)
helper.append(win_7)
helper.append(win_6)
helper.append(win_5)
helper.append(win_4)
helper.append(win_3)
helper.append(win_2)
helper.append(win_1)
helper.append(win_0)
if number_of_com % 2 == 0:
c = 1
while c <= loop:
even()
c += 1
else:
c = 1
while c <= loop:
odd()
c += 1
采纳答案by Tim Pietzcker
You can't reshuffle a dictionary. What you cando is create a list of the dictionary's keys and shuffle thatin order to achieve a new arbitrary order in which to access the dictionary's contents:
你不能重新整理字典。您可以做的是创建一个字典键的列表并对其进行洗牌,以实现访问字典内容的新任意顺序:
>>> import random
>>> d = {1:2, 3:4, 5:6, 7:8, 9:10}
>>> d
{1: 2, 3: 4, 9: 10, 5: 6, 7: 8}
>>> keys = list(d.keys()) # Python 3; use keys = d.keys() in Python 2
>>> random.shuffle(keys)
>>> [(key, d[key]) for key in keys]
[(1, 2), (5, 6), (7, 8), (9, 10), (3, 4)]
>>> random.shuffle(keys)
>>> [(key, d[key]) for key in keys]
[(9, 10), (3, 4), (1, 2), (7, 8), (5, 6)]
>>> random.shuffle(keys)
>>> [(key, d[key]) for key in keys]
[(1, 2), (7, 8), (3, 4), (5, 6), (9, 10)]
回答by koffein
Randomly assign keys to values:
将键随机分配给值:
from random import shuffle
x = dict(a=1, b=2, c=3, d=4)
# py2.7
values = x.values()
# py3.*
values = list( x.values() )
# It does not make any difference, whether values or keys are shuffled
# but it could lead to wrong conclusions to shuffle the keys.
shuffle(values)
y = dict(zip(x.keys(), values))
# py2.7
print y
# py3.*
print(y)
Output
输出
{'a': 1, 'c': 4, 'b': 2, 'd': 3}
回答by koffein
You can't order the built-in dict
, but in the collections
module there is OrderedDict
:
您不能订购 built-in dict
,但在collections
模块中有OrderedDict
:
>>> from collections import OrderedDict
>>> from random import random
>>> od = OrderedDict(a=1, b=2, c=3, d=4)
>>> # sorts a list by whatever the key-callable returns => its randomly sorted
>>> shuffled_key_value_list = sorted(od.items(), key=lambda x: random())
>>> shuffled_key_value_list # (this might also do it)
[('d', 4), ('c', 3), ('a', 1), ('b', 2)]
>>> OrderedDict(shuffled_key_value_list)
OrderedDict([('d', 4), ('c', 3), ('a', 1), ('b', 2)])
回答by Piotr Kamoda
Well I think that you can also do it simpler, without lambdas etc.:
好吧,我认为你也可以做得更简单,没有 lambdas 等:
from random import shuffle
from collections import OrderedDict
a = {num-97:chr(num) for num in range(97, 107)}
# a = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j'}
b = list(a.items())
shuffle(b)
a = OrderedDict(b) #Or just stay with b
# a = OrderedDict([(1, 'b'), (6, 'g'), (4, 'e'), (3, 'd'), (5, 'f'), (8, 'i'), (2, 'c'), (7, 'h'), (9, 'j'), (0, 'a')])
# b = [(1, 'b'), (6, 'g'), (4, 'e'), (3, 'd'), (5, 'f'), (8, 'i'), (2, 'c'), (7, 'h'), (9, 'j'), (0, 'a')]
I think that using shuffle makes the code clearer then using sorted with random key.
我认为使用 shuffle 使代码更清晰,然后使用随机键排序。
For shuffling keys only it would make something like:
仅对于洗牌键,它会产生类似的东西:
keys = list(a.keys())
shuffle(keys)
OrderedDict(zip(keys, a.values()))
# OrderedDict([(3, 'a'), (1, 'b'), (9, 'c'), (4, 'd'), (6, 'e'), (8, 'f'), (0, 'g'), (2, 'h'), (5, 'i'), (7, 'j')])
回答by Ali
I saw that guys twisted this simple question (if I get it though). To shuffle the contents of a dictionary lets say
我看到人们扭曲了这个简单的问题(如果我明白的话)。打乱字典的内容让我们说
a={'a':1,'b':2,'c':3}
we can do in three simple steps:
我们可以通过三个简单的步骤来完成:
listing the items of given dictionary
a1 = list(a.items())
Out[1]: [('a', 1), ('b', 2), ('c', 3)]
shuffling the items list
numpy.random.shuffle(a1)
Out[2]: [('b', 2), ('c', 3), ('a', 1)]
getting shuffled dictionary
a = dict(a1)
Out[3]: {'b': 2, 'c': 3, 'a': 1}
列出给定字典的项目
a1 = 列表(a.items())
输出[1]: [('a', 1), ('b', 2), ('c', 3)]
洗牌项目列表
numpy.random.shuffle(a1)
输出[2]: [('b', 2), ('c', 3), ('a', 1)]
得到洗牌字典
a = dict(a1)
出[3]:{'b':2,'c':3,'a':1}
回答by blhsing
If you're using Python 3.7, where dicts are officially ordered, you can convert the dict items to a list of tuples for shuffling before converting it back to a dict with the dict()
constructor:
如果您使用的是 Python 3.7,其中 dicts 是正式排序的,您可以将 dict 项转换为元组列表以进行混洗,然后再将其转换回带有dict()
构造函数的 dict :
import random
d = {'a':1, 'b':2, 'c':3, 'd':4}
l = list(d.items())
random.shuffle(l)
d = dict(l)