我使用 random.shuffle 是错误的还是这是一个错误?
Am I using random.shuffle wrong or is this a bug?
所以我在拆分列表之前将其洗牌。它是从文件中读取的数字列表,因此该列表实际上是字符串列表,但它们是数字:
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_old = "0,1,2,3,4,5,6,7,8,9"
streams = ['0','1','2','3','4','5','6','7','8','9']
print(streams, type(streams[0]))
import random
random.shuffle(streams)
另一种方式可能是:
streams = "0,1,2,3,4,5,6,7,8,9"
new_streams = streams.split(',')
import random
random.shuffle(new_streams)
print(new_streams)
所以我在拆分列表之前将其洗牌。它是从文件中读取的数字列表,因此该列表实际上是字符串列表,但它们是数字:
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_old = "0,1,2,3,4,5,6,7,8,9"
streams = ['0','1','2','3','4','5','6','7','8','9']
print(streams, type(streams[0]))
import random
random.shuffle(streams)
另一种方式可能是:
streams = "0,1,2,3,4,5,6,7,8,9"
new_streams = streams.split(',')
import random
random.shuffle(new_streams)
print(new_streams)