根据Python列表中的值返回字符串值

时间:2019-03-19 02:54:35

标签: python list conditional

生成随机数为0和1的列表

decision = [0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0]

我想生成另一个列表,该列表在决策中返回“通过”值是1,如果值是0则返回“失败”

['fail', 'fail', 'pass', 'pass', 'pass', 'fail', 'fail', 'pass',....'fail']

我尝试使用

进行列表理解
newlist = ["pass" for k in decision if k == 0] 

但是如果k==1,我想不出一种方法来整合其他条件。

请帮助。

3 个答案:

答案 0 :(得分:3)

在理解的值部分中使用条件”

newlist = ["pass" if k == 1 else "fail" for k in decision]

或者,如果您有更多值,请创建字典:

res_dict = {
    0  : "Equal",
    1  : "Higher",
    -1 : "Lower",
}

newlist = [res_dict.get(x) for x in decision]

答案 1 :(得分:2)

我知道我的答案不是您想要的,但是我相信,如果您仅使用TrueFalse,它将更容易。这里的代码:

decision = [0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0]
result = [d == 1 for d in decision] # // So 1 will be True and 0 will be False

答案 2 :(得分:0)

counter=0
otherlist=[]
for element in mylist:
    if element == 0:
        otherlist[counter]="fail"
    else:
        otherlist[counter]="pass"
    counter += 1

它不使用理解,但是可以解决问题。希望这可以帮助。 甚至更快的选择是:

otherlist = []
for element in mylist:
    if element == 0:
        otherlist.append("fail")
    else:
        otherlist.append("pass")

您还可以允许0代表False和1代表True

otherlist = []
for element in mylist:
    if element == 0:
        otherlist.append(False)
    else:
        otherlist.append(True)