【问题标题】:Changing for loop to while loop for non-range for loops将 for 循环更改为 while 循环以进行非范围 for 循环
【发布时间】:2018-11-19 03:47:43
【问题描述】:
for item in lst[0:]:
    temp1 = int(item[1])
    temp2 = int(item[2])

这是一个代码块,表示列表中每个元素的项目。 我将如何更改它以便搜索列表中的每个项目但使用 while 循环?

【问题讨论】:

  • 这完全可以作为for 循环。为什么要搞这个?你试过什么?您具体需要哪些帮助?

标签: python for-loop while-loop


【解决方案1】:

这就是你所拥有的:

for item in lst:
    temp1 = int(item[1])
    temp2 = int(item[2])

如果您想使用列表索引而不是列表项本身,您可以这样做:

for idx in range(len(lst)):
    temp1 = int(lst[idx][1])
    temp2 = int(lst[idx][2])

range() 本质上返回一个列表[1, 2, 3, ...],它会被迭代(它的实际工作方式更复杂,但你明白了)。制作while 循环或多或少是相同的,只是您必须自己使用算术进行迭代:

idx = 0
end = len(lst)
while idx < end:
    temp1 = int(lst[idx][1])
    temp2 = int(lst[idx][2])
    idx += 1

【讨论】:

    猜你喜欢
    • 2014-03-15
    • 2018-08-13
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多