In [120]: import random In [121]: l1 = (1, 2, 3) In [122]: l2 = [1, 2, 3] In [123]: ran random range In [123]: random.shuffle(l1) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-123-00db8a674af6> in <module>() ----> 1 random.shuffle(l1) /usr/lib/python2.7/random.pyc in shuffle(self, x, random) 287 # pick an element in x[:i+1] with which to exchange x[i] 288 j = _int(random() * (i+1)) --> 289 x[i], x[j] = x[j], x[i] 290 291 def sample(self, population, k): TypeError: ‘tuple‘ object does not support item assignment In [124]: random.shuffle(l2) In [125]: l2 Out[125]: [3, 2, 1]
In [126]: a = l2 In [127]: a Out[127]: [3, 2, 1] In [128]: a = random.shuffle(l2) In [129]: a In [130]: a In [131]: print a None
上面的错误是因为元组内容不可更改
下面返回a的值是None是因为shuffle返回值的原因 ,shuffle只是在原基础上做的打乱
时间: 2024-09-30 21:57:36