Python错误集锦: 调用random.choice()发生IndexError: Cannot choose from an empty sequence

原文链接:http://www.juzicode.com/archives/4535

错误提示:

 调用random.choice()发生IndexError: Cannot choose from an empty sequence

#juzicode.com / vx公众号:桔子code
import  random
seed=[]
num = random.choice(seed)
print('random num=',num)
==========运行结果:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-33-59aa68b0370d> in <module>
      2 import  random
      3 seed=[]
----> 4 num = random.choice(seed)
      5 print('random num=',num)

d:\python\python38\lib\random.py in choice(self, seq)
    288             i = self._randbelow(len(seq))
    289         except ValueError:
--> 290             raise IndexError('Cannot choose from an empty sequence') from None
    291         return seq[i]
    292 

IndexError: Cannot choose from an empty sequence

 

错误原因:

1、作为random.choice()入参的“种子”序列为空,导致IndexError 

解决方法:

1、用非空列表、元组、字符串等赋值seed变量

#juzicode.com / vx公众号:桔子code
import  random
seed=[1,2,3,5,6,7,8,9,0]
num = random.choice(seed)
print('random num=',num)
seed=(1.0,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9)
num = random.choice(seed)
print('random num=',num)
seed='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
num = random.choice(seed)
print('random num=',num)
==========运行结果:
random num= 6 
random num= 5.5 
random num= V

扩展内容:

  1.  
  2.  

 


 

如果本文还没有完全解决你的疑惑,你也可以在微信公众号:“桔子code”后台留言撩我,我会尽我所能为你答疑解惑

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注