python - 我使用 random.shuffle 是错误的还是这是一个错误?

标签 python random shuffle

所以我在拆分列表之前先对其进行洗牌。它是从文件中读取的数字列表,因此该列表实际上是字符串列表,但它们是数字:

streams = ['0','1','2','3','4','5','6','7','8','9']

现在,我运行的代码只是简单地打乱列表:

print(streams, type(streams[0]))
import random
random.shuffle(streams)

顺便说一句,我正在使用Python 3.6.4。这是我收到的错误:

C:\src>python cli.py
0,1,2,3,4,5,6,7,8,9
 <class 'str'>
Traceback (most recent call last):
...
  File "....py", line 3, in split_randomized_list
    random.shuffle(streams)
  File "C:\ProgramData\Anaconda3\lib\random.py", line 275, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'str' object does not support item assignment

这对我来说,它不能随机播放由字符串格式的数字组成的列表?是对的吗?这是一个错误还是我做错了?

最佳答案

另一种方式可能是:

streams = "0,1,2,3,4,5,6,7,8,9"
new_streams = streams.split(',')
import random
random.shuffle(new_streams)
print(new_streams)

关于python - 我使用 random.shuffle 是错误的还是这是一个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51567292/

相关文章:

java - 性能改进(生成任意长度的随机字符串)

java - Collections.shuffle(列表列表)

python - 如何将 django-hosts 与 Nginx 一起使用

python - 选择具有 bs4 的一个或多个特定属性的 HTML 标签

php - 从数组 php 中获取随机值的子集

c++ - std::shuffle 不能用 std::list 编译

java - Shuffle 在 Java 中不工作

python - 在 jython 2.1 中运行外部命令并控制输入/输出

python - FastText .bin 文件无法装入内存,即使我有足够的 RAM

java - 创建一个随机向定义的终点移动的 Java Point 数组