简体   繁体   English

列表(数组)中某个范围内的随机样本| Python 3.x

[英]Random sample within a certain range in a list (array) | Python 3.x

I have a list with many characters in it like such: 我有一个包含许多字符的列表,例如:

list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q',
        'r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9',
        '0'," ",'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
        'Q','R','S','T','U','V','W','X','Y','Z']

I want the program to randomly pick 8 characters within the first 26 (lowercase letters) items in my list. 我希望程序在列表的前26个(小写字母)项目中随机选择8个字符。 I will not delete or separate the other items in this array as I need them later for a similar thing. 我不会删除或分隔此数组中的其他项,因为以后我需要它们来处理类似的事情。

I am somewhat new to programming and I prefer a simple solution, although I am not stopping you from putting something more complex out there for others to see. 我对编程有些陌生,我更喜欢一种简单的解决方案,尽管我并没有阻止您在此发布更复杂的内容供其他人查看。

Thanks in advance! 提前致谢!

您可以切片该数组以对其进行采样。

random.sample(seq[:26], k=8)

Firsty you need the random module : 首先,您需要使用random模块

import random

Then I would use this solution: 然后,我将使用以下解决方案:

your_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q',
        'r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9',
        '0'," ",'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
        'Q','R','S','T','U','V','W','X','Y','Z']

first_26_characters = your_list[0:26] # get items from 0 to 26 in new list
random.shuffle(first_26_characters) # shuffle new list
random_8_characters = first_26_characters[0:8] # get first 8 characters because after shuffle they are random

I hope this helps! 我希望这有帮助!

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

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