在尝试用 Python 编程中,我遇到了这样一个问题:我想让用户指定一个公司中股东的数量,然后询问每位股东在三个品质上的评级(工作的有用性、工作的意义和工作的难度)。我想把用户的这些评级数据存储起来,以便以后显示。为了解决这个问题,我尝试使用三个不同的列表来分别存储这三个品质的评级,并使用一个变量 userrem 作为标识符来向每个列表中添加项目。然而,在执行代码时,我遇到了 IndexError: list assignment index out of range 的错误。
2、解决方案
这个问题有几个不同的解决方法:
-
使用字典代替列表。字典是一种更灵活的数据结构,它允许使用变量作为键来访问其中的值。这样,就可以轻松地向字典中添加新的项目,而无需担心索引越界的问题。
-
使用列表推导式。列表推导式是一种简洁的语法,可以用来创建列表。使用列表推导式,可以将输入的数据直接转换为列表中的项目,而无需使用循环。
-
预先创建列表。如果知道列表中项目的数量,可以预先创建列表,然后向其中添加项目。这样可以避免出现索引越界的问题。
-
使用元组。元组是一种不可变的数据类型,可以用来存储多个值。可以使用元组来存储每个股东的三个评级,然后将元组添加到列表中。
下面是一个使用字典的示例代码:
usefulness = {}
significance = {}
difficulty = {}
user_n = int(input('How many shareholders are there?'))
for i in range(user_n):
userrem = i
usefulness[userrem] = int(input('Rate the usefulness of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
significance[userrem] = int(input('Rate the significance of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
difficulty[userrem] = int(input('Rate the difficulty of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
print(usefulness)
print(significance)
print(difficulty)
下面是一个使用列表推导式的示例代码:
user_n = int(input('How many shareholders are there?'))
usefulness = [int(input('Rate the usefulness of the work performed by shareholder# '+str(i+1)+' [Range=0-5]')) for i in range(user_n)]
significance = [int(input('Rate the significance of the work performed by shareholder# '+str(i+1)+' [Range=0-5]')) for i in range(user_n)]
difficulty = [int(input('Rate the difficulty of the work performed by shareholder# '+str(i+1)+' [Range=0-5]')) for i in range(user_n)]
print(usefulness)
print(significance)
print(difficulty)
下面是一个预先创建列表的示例代码:
user_n = int(input('How many shareholders are there?'))
usefulness = [None] * user_n
significance = [None] * user_n
difficulty = [None] * user_n
for i in range(user_n):
userrem = i
usefulness[userrem] = int(input('Rate the usefulness of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
significance[userrem] = int(input('Rate the significance of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
difficulty[userrem] = int(input('Rate the difficulty of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
print(usefulness)
print(significance)
print(difficulty)
下面是一个使用元组的示例代码:
user_n = int(input('How many shareholders are there?'))
scores = []
for i in range(user_n):
userrem = i
usefulness = int(input('Rate the usefulness of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
significance = int(input('Rate the significance of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
difficulty = int(input('Rate the difficulty of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
scores.append((usefulness, significance, difficulty))
print(scores)
建议选择最适合您具体需求的解决方案。