繁体   English   中英

Python-替换列表中的特定数字

[英]Python - replacing specific numbers in a list

我有一份问卷调查的分数:

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

如果有人可以提供帮助,我将不胜感激。 提前致谢

这将创建一个新列表,并纠正必要的分数。

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列表中索引的分数的Rscores

我重命名了您的列表,以避免“遮盖” Python类型的名称。 如果将Rscores作为一组,则您的代码运行速度可能会稍微快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)

希望对你有帮助

在此处输入图片说明

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 。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM