【问题标题】:Finding index by while loop通过while循环查找索引
【发布时间】:2018-04-19 01:25:33
【问题描述】:

如何通过 while 循环(不是 for)从列表中打印索引?

示例 1:

Lst=[1,2,3,4,5]

c=2

在这种情况下,我希望 python(2.7) 打印 Lst 中可以除以 c 的数字索引。 (lst[1],lst[4])

示例 2:

Lst=[1,3,3,3,5]

c=2

在这种情况下,我希望 python(2.7) 打印 'None'。

【问题讨论】:

  • 我回答了,但忽略了“by while loop”部分,这使您的问题成为“为我的家庭作业编写一个愚蠢的代码”问题。自己做。注意:对于这类事情,while 循环是最糟糕的控制结构。

标签: python python-2.7 indexing while-loop


【解决方案1】:

这正是您要找的:

#!/usr/bin/env python

Lst = [1,2,3,4,5]

c=2
i = 0
res = []
while i in range(len(Lst)):
        if Lst[i] % 2 == 0:
                res.append(Lst[i])
        i+=1
if len(res) > 0:
        print res
else:
        print "None"

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2013-03-19
    • 2020-08-19
    • 2020-10-10
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多