简体   繁体   English

如何将列表中的元素随机分配给坐标?

[英]How to randomly assign elements from a list to coordinates?

Sumlist = ['9', '2', '7', '1', '5', '3', '4', '6', '8', '$', '$', '$', '$', '$', 'K', 'I', 'Q', 'J', 'T', 'V', 'D', 'B', 'R', 'Y', 'L', 'Z', 'U', 'P', 'A', 'W', 'C', 'O', 'G', 'M', 'H', 'S', 'N', 'E', 'X', 'F']

And let's say given some coordinates such as: 假设有一些坐标,例如:

gridxy = [1,2] [1,3] [1,4] [2,2] [2,3] [2,4]

Now my question comes: How does i randomly assign the elements in my Sumlist to each of my coordinates through python? 现在我的问题来了:我如何通过python将我的摘要列表中的元素随机分配给我的每个坐标? Do i use if and else statement? 我是否使用if和else语句?

I don't think I will be using tuples in this one. 我不认为我会在这个中使用元组。

You should use the random module to randomly sample your Sumlist and associate each element to the element in gridxy using the zip builtin function : 您应该使用random模块对Sumlist进行随机sample ,并使用zip内置函数将每个元素与gridxy中的元素相关联:

Tested on Python 2.7.9

>>> import random
>>> Sumlist = ['9', '2', '7', '1', '5', '3', '4', '6', '8', '$', '$', '$', '$', '$', 'K', 'I', 'Q', 'J', 'T', 'V', 'D', 'B', 'R', 'Y', 'L', 'Z', 'U', 'P', 'A', 'W', 'C', 'O', 'G', 'M', 'H', 'S', 'N', 'E', 'X', 'F']
>>> gridxy = [[1,2],[1,3],[1,4],[2,2],[2,3],[2,4]]
>>> random.seed()
>>> zip(gridxy, random.sample(Sumlist, len(gridxy)))
[([1, 2], '$'), ([1, 3], '1'), ([1, 4], '6'), ([2, 2], 'X'), ([2, 3], '$'), ([2, 4], '$')]

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

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