Python替换lis中的特定数字

2024-04-20 05:21:44 发布

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

我从问卷中得到了分数:

list= [1, 2, 2, 4, 1, 4, 1, 3, 2, 2, 2, 1, 1, 1, 4, 3, 4, 2, 1, 1, 1, 1, 1, 2, 2, 2, 4, 1, 4, 1, 2, 4, 4, 4, 4, 4, 2, 3, 2, 3, 3, 3]

某些问题需要逆向评分。 “Rscores”是需要反向评分的索引列表,这意味着对于这些分数,如果是1,则需要用4替换,如果是2,则需要用3替换。你知道吗

Rscores = [1, 6, 11, 16, 21, 28, 33, 38, 43, 49, 57, 8, 46, 2, 7, 12, 17, 22, 25, 35, 40]

我试过这个方法,还有很多不同的方法,但都不管用:

for Rscores in list:
    if list[Rscores] == 1:
        list[Rscores] = 4
    elif list[Rscores] == 2:
        list[Rscores] = 3
    elif list[Rscores] == 3:
        list[Rscores] = 2
    elif list[Rscores] == 4:
        list[Rscores] = 1

如果有人能帮忙,我将非常感激。 提前谢谢


Tags: 方法in列表forif评分分数list
3条回答

这将创建一个新列表,并更正必要的分数。你知道吗

lst= [1, 2, 2, 4, 1, 4, 1, 3, 2, 2, 2, 1, 1, 1, 4,
      3, 4, 2, 1, 1, 1, 1, 1, 2, 2, 2, 4, 1, 4, 1,
      2, 4, 4, 4, 4, 4, 2, 3, 2, 3, 3, 3]

Rscores = [1, 6, 11, 16, 21, 28, 33, 38, 43, 49, 57,
           8, 46, 2, 7, 12, 17, 22, 25, 35, 40]

rectified_scores = [5-x if i in Rscores else x for i, x in enumerate(lst)]

enumerate产生一个成对序列(i,x),其中i是元素索引,x是它的值。5-x if i in Rscores else x是标准索引的得分,是Rscores列表中索引得分的倒数。你知道吗

我重命名了您的列表以避免“隐藏”Python类型的名称。如果Rscores是一个集合,您的代码可能会运行得稍微快一点,但它并不需要优化。你知道吗

它在工作

list= [1, 2, 2, 4, 1, 4, 1, 3, 2, 2, 2, 1, 1, 1, 4, 3, 4, 2, 1, 1, 1, 1, 1, 2, 2, 2, 4, 1, 4, 1, 2, 4, 4, 4, 4, 4, 2, 3, 2, 3, 3, 3]

for n, i in enumerate(list):
    if i == 1:
        list[n] = 4
    if i == 2:
        list[n] = 3
    if i == 3:
        list[n] = 2
    if i == 4:
        list[n] = 1
print(list)

希望能帮上大忙

enter image description here

L = [1, 2, 2, 4, 1, 4, 1, 3, 2, 2, 2, 1, 1, 1, 4, 3, 4, 2, 1, 1, 1, 1, 1, 2, 2, 2, 4, 1, 4, 1, 2, 4, 4, 4, 4, 4, 2, 3, 2, 3, 3, 3]
Rscores = [1, 6, 11, 16, 21, 28, 33, 38, 43, 49, 57, 8, 46, 2, 7, 12, 17, 22, 25, 35, 40]

def reverseScore(score):
    if score == 1:
        return 4
    elif score == 2:
        return 3
    elif score == 3:
        return 2
    elif score == 4:
        return 1

def rscoredList(L):
    for idx in Rscores:
        if idx < len(L):
            L[idx] = reverseScore(L[idx])
    return L

L = rscoredList(L)

我认为您列出的示例中的一个问题是,Rscores中的索引超出了列表的范围。(57被列为要反转的索引,但它不能被反转,因为len(L)==42。)

相关问题 更多 >