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

查看:28
本文介绍了在 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天全站免登陆