想要使用if else语句从现有列表中创建一个新列表

时间:2019-07-15 08:00:10

标签: python list if-statement jupyter-notebook list-comprehension

  

我想使用现有列表“ dta”创建一个新列表,在该列表中,我不需要“香蕉”的值,但不需要其他的数字。   所需列表如下:

[1,3,4,5,6]

但是当我尝试打印我的最终列表“ d”时,我只会得到单个值。

dta=list(["apple","banana","pine","cucumber","Guava","Coconut"])

d=[]
def cont_list(x):

for i in x:
    if i=="banana":
        continue
if i=="pine":
    d.append(3)

elif i=="apple":
    d.append(1)

elif i=="cucumber":
    d.append(4)
elif i=="Guava":
    d.append(5)
else:
    d.append(6)

return d   

cont_list(dta)
print(d)

2 个答案:

答案 0 :(得分:2)

您可以通过列表理解来做到这一点:

dta = ["apple","banana","pine","cucumber","Guava","Coconut"]

d = [idx for idx in range(1,len(dta)+1) if dta[idx-1] != "banana"]
print (d)

功能:

dta = list([“苹果”,“香蕉”,“松树”,“黄瓜”,“番石榴”,“椰子”])

def cont_list(x):
    dta = ["apple","banana","pine","cucumber","Guava","Coconut"]
    d = [idx for idx in range(1,len(dta)+1) if dta[idx-1] != "banana"]
    return d
print (cont_list(dta))

输出:

[1, 3, 4, 5, 6]

注意:如果您修复了INDENTION,您的代码就可以了:

d=[]
def cont_list(x):

    for i in x:
        if i=="banana":
            continue
        if i =="pine":
            d.append(3)

        elif i=="apple":
            d.append(1)

        elif i=="cucumber":
            d.append(4)
        elif i=="Guava":
            d.append(5)
        else:
            d.append(6)
    return d

cont_list(dta)
print(d)

或者您也可以这样做:

d=[]
def cont_list(x):

    for i in range(len(x)):
        if x[i]=="banana":
            continue
        else:
            d.append(i+1)
    return d

cont_list(dta)
print(d)

答案 1 :(得分:1)

似乎您想使用项目的索引(加1)...这可以通过简单的列表理解来完成:

dta = ["apple","banana","pine","cucumber","Guava","Coconut"]
d = [dta.index(e) + 1 for e in dta if e != 'banana']

或使用enumerate(如果列表很大,我希望这会更快):

dta = ["apple","banana","pine","cucumber","Guava","Coconut"]
d = [i for i, e in enumerate(dta, 1) if e != 'banana']