IndexError:使用random.sample列出索引超出范围

时间:2014-03-15 20:18:53

标签: python-3.x

import time
import random
a = [random.sample(xrange(10), 10)]
b = int(input('Enter phone number digit 1 to encrypt'))
c = a[b]
d = int(input('Enter phone number digit 2 to encrypt'))
e = a[d]
f = int(input('Enter phone number digit 3 to encrypt'))
g = a[f]
h = int(input('Enter phone number digit 4 to encrypt'))
i = a[h]
j = int(input('Enter phone number digit 5 to encrypt'))
k = a[j] 
l = int(input('Enter phone number digit 6 to encrypt'))
m = a[l]
n = int(input('Enter phone number digit 7 to encrypt'))
o = a[n]
p = int(input('Enter phone number digit 8 to encrypt'))
q = a[p]
r = int(input('Enter phone number digit 9 to encrypt'))
s = a[r]
t = int(input('Enter phone number digit 10 to encrypt'))
u = a[t]

b = str(b)
d = str(d)
f = str(f)
h = str(h)
j = str(j)
l = str(l)
n = str(n)
p = str(p)
r = str(r)
t = str(t)


print('This is your original phone number: ')
time.sleep(1)
print(b+d+f+h+j+l+n+p+r+t)
print('This is your encrypted phone number')
time.sleep(1)
print(c,e,g,i,k,m,o,q,s,u)

即使我输入一个10以下的数字,如4或2,当它询问我的程序的第一个数字时,它会给我一个错误。这是下面的错误。我知道这个程序整体糟透了,并且随机模块不应该用于加密,但我制作了这个程序来测试我对random.sample模块的技能。

c = a[b]
IndexError: list index out of range 

1 个答案:

答案 0 :(得分:0)

您的代码可以大大简化,删除所有未明确命名的变量,重复和IndexError的风险

import random
import string

digits = random.sample(range(10), 10)

phone = input("Enter a phone number: ")
encrypt = [digits[int(c)] for c in phone if c in string.digits]

print("Here is the encrypted phone number: {0}".format("".join(map(str, encrypt))))

目前,如果用户输入两个(或更多)数字,您将超过a的结尾。

您也可以使用list.index轻松解密:

phone = [digits.index(i) for i in encrypt]