【问题标题】:Am I using random.shuffle wrong or is this a bug?我使用 random.shuffle 错误还是这是一个错误?
【发布时间】:2018-07-28 01:30:27
【问题描述】:

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

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

这告诉我它不能随机播放由字符串格式的数字组成的列表?那正确吗?这是一个错误还是我做错了?

【问题讨论】:

  • @U9-Forward 你用的是什么版本的python?
  • 我觉得版本不重要,我的版本是python-3.6.0
  • 你不是在洗牌。您正在尝试对字符串进行洗牌。字符串不是列表。

标签: python random shuffle


【解决方案1】:

另一种方式可能是:

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

【讨论】:

    【解决方案2】:

    我想我已经成功复制了您的错误,我已将您的流更改为列表。

    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)
    

    【讨论】:

    • 哦,谢谢,我想我以为它是一个列表,而实际上它不是
    • @LegitStack 在您的问题中输入streams = ['0','1','2','3','4','5','6','7','8','9'] 非常具有误导性......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多