如何使用变量作为标识符来输入列表中的项目?

2024-04-25 01:54:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个不错的C++背景,但我对Python是新手。我正在尝试编写一个基本程序,允许用户指定一家公司的股东人数,然后询问每个股东对三种素质(工作的有用性、工作的重要性、工作的难度)的评级。你知道吗

我想把用户的评分存储在这三个刻度上的某个地方,然后再显示出来。我仍然不确定是否使用3个列表的3个质量是最有效的方式做到这一点。无论如何,我在下面的代码中尝试的是分配一个变量userrem作为标识符,使用它添加列表中的新项。你知道吗

例如,userrem的初始值是0。因此,我的理解是usefulness[userrem] = input()应该将输入的值添加为列表中的第一项。然后,正如您在代码中看到的那样,while循环继续,并且userrem增加了1。所以我认为对于循环的第二次迭代,usefulness[userrem]=input()应该添加输入值作为列表中的第二项。你知道吗

但是,在循环的第一次迭代中将值输入到usefulness[userrem]之后,我一直得到错误IndexError: list assignment index out of range。你知道吗

所以,我的问题是如下所示:你知道吗

  1. 使用列表是最有效的方法吗?你知道吗
  2. 有什么方法可以实现我想要的目标呢?你知道吗
  3. 如果每个股东都有一份名单,上面有三个名字,会更好吗 三种品质的每一项,而不是有三个带有 未知数量的项目(可能无限!)?但如果我们有名单 对于每个股东来说,名单的数量可能是未知的 即使每个列表中的项目只有3个,也可能是无限的。 如何确定哪种方法最有效?你知道吗

谢谢!你知道吗

def func_input():  
    userrem=0 # Variable used as the identifier while adding items to the lists
    global user_n # Total number of users, accessed during input
    user_n=0 
    user_n=int(input('How many shareholders are there?'))
    while userrem<user_n:
        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]'))
        userrem=userrem+1

Tags: ofthe方法列表inputrateintwork
1条回答
网友
1楼 · 发布于 2024-04-25 01:54:22

做你想做的事情最简单的方法就是从列表改成字典:

usefulness = {}
significance = {}
difficulty = {}

它使用与访问列表相同的语法,并允许分配给以前未分配的索引。你知道吗

如果您想继续使用一个列表,则需要输入另一个变量,然后append到该列表,或者提前创建所需大小的列表。你知道吗

您可以将这3个值组合成一个元组或列表,并将其存储在单个列表/字典中,而不是使用3个列表或字典。下面是一些用于演示在列表中存储元组的代码:

scores = [None]*user_n
for userrem in range(user_n):
    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[userrem] = (usefulness, significance, difficulty)

相关问题 更多 >