如何为可变长度的列表编写条件语句?

2024-04-29 12:14:56 发布

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

如果我有一个列表ls,它在每次调用一个特定的函数时长度不同,那么写If条件的有效方法应该是什么 写同样的东西有效率吗?你知道吗

谢谢。你知道吗

我试过这个:

a = []
if len(ls)==3 :
    if len(ls) ==1 :

        if len(ls[0])==3 :
            b = 0
            a.append (b)
            print("done1")
    if len(ls)==2 :
        if len(ls[0]) ==3 :
            b = 0
            a.append (b)
            print("done1")
        if len(ls[1]) ==3 :
            b = 2
            a.append (b)
            print("done2")
    if len(ls) ==3 :

        if len(ls[0]) ==3 :
            b = 0
            a.append (b)
            print("done1")
        if len(ls[1]) ==3 :
            b = 2
            a.append (b)
            print("done2")
        if len(ls[2])==3:
            b =3
            a.append (b)
            print("done 3")

这些代码行将返回不同长度的列表“ls”的列表“a”b“只是我加的一个随机值。”b”不是索引值。有没有其他有效的方法来编写相同的代码?你知道吗


Tags: 方法函数代码列表lenif条件ls
2条回答

根据您的意见,我认为您需要:

for index, item in enumerate(ls):
    if len(item) == 3: # or len(item) == len(ls) ??
        b = index+1 # Or b = index , as you need 
        a.append(b)
        print("done {}".format(b))

如果IndexError是原因,您可能应该考虑使用循环:

for l in ls:
    b = len(l)
    a.append(b)
    print("done {}".format(b))
    # Alternatively, print("done %d" % (b,))

相关问题 更多 >