【问题标题】:How to compare an array value with another explicit value in python如何将数组值与python中的另一个显式值进行比较
【发布时间】:2016-09-29 21:19:06
【问题描述】:

我想做这样的事情

while(x<100 for x in someList):
    if someList has a value more than 100
    the loop should end.

【问题讨论】:

标签: python loops compare


【解决方案1】:

这也将在值大于 100 时结束循环

for x in someList:
    if x > 100:
        break

你可以试试这个:

i=0
while ((i<len(someList)) and (someList[i] <= 100) ):
  '''Do something'''
  i+=1

【讨论】:

  • 我想要一个单行的答案。我可以在循环条件中添加一些东西。
【解决方案2】:

可以使用itertools.takewhile:

for x in takewhile(lambda x: x <= 100, someList):
    print(x)

但我认为@sinsuren 的break 解决方案是最好的。当我不想要循环时,我只会使用takewhile,例如在sum(takewhile(lambda x: x &lt;= 100, someList))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2016-08-26
    • 1970-01-01
    相关资源
    最近更新 更多