在Python中随机化字符串列表的最佳方法 [英] Best way to randomize a list of strings in Python

查看:125
本文介绍了在Python中随机化字符串列表的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个字符串列表作为输入,并且需要返回具有这些相同字符串但以随机顺序排列的列表.我必须允许重复-同一字符串在输入中可能出现一次或多次,并且在输出中必须出现相同的次数.

I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.

我看到了几种强力"方式(使用循环,禁止使用),我目前正在使用其中一种方式.但是,知道Python可能会完成一项工作,对吧?

I see several "brute force" ways of doing that (using loops, god forbid), one of which I'm currently using. However, knowing Python there's probably a cool one-liner do get the job done, right?

推荐答案

>>> import random
>>> x = [1, 2, 3, 4, 3, 4]
>>> random.shuffle(x)
>>> x
[4, 4, 3, 1, 2, 3]
>>> random.shuffle(x)
>>> x
[3, 4, 2, 1, 3, 4]

这篇关于在Python中随机化字符串列表的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆