gpt4 book ai didi

python - 我怎样才能在 python 中停止循环迭代

转载 作者:行者123 更新时间:2023-11-29 12:07:41 31 4
gpt4 key购买 nike

我想在我的代码中执行几行后停止 for 循环

cursor.execute("select score*100 from daily_stats1 where  user_id=102")
rows = cursor.fetchall()
# Convert query to objects of key-value pairs
lastweek1 = list()
i = 0
for row in rows:
lastweek1.append(row[i])
if i == 4:
break

最佳答案

您从未增加您的i。要么这样做,要么留给 enumerate。此外,根据您的说明,您只想打印 4 行,您最好在循环的顶部进行检查,否则您将打印 5 行:

lastweek1 = list()
for i, row in enumerate(rows):
if i == 4:
break
lastweek1.append(row)

或者您无法将其复杂化 :)。前四整行很简单

lastweek1 = rows[:4]

或者如果它是一个生成器(这很可能)并且您需要具体化它,

lastweek1 = list(rows[:4])

关于python - 我怎样才能在 python 中停止循环迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53408271/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com