问题描述
限时送ChatGPT账号..我正在尝试在 python 中运行 while true
循环,以检查我想要的单词是否与我拥有的数据帧的特定单元格中的单词相同.我尝试了两种方法.第一个如下:
I am trying to run a while true
loop in python to check if the word I want is same as that in a specific cell of the dataframe I have. I tried in two ways. First one is as below:
while True:
try:
df1 = pd.read_csv(io.StringIO(dfs[4].to_csv(index=False)), skiprows=1, header=[0,1])
c = df1.iat[1,3]
print(c)
if (c == "Margaret"):
df1.to_csv("break.csv", mode='a', header=False)
print("Margaret found")
break
except Exception as e:
print("waiting...")
continue
break
但是当值不可用时,它不会再试一次,而是继续打印waiting...";无止境.
But when the value is not available, instead of trying again, it keeps printing "waiting..." endlessly.
然后我尝试如下:
while True:
try:
df1 = pd.read_csv(io.StringIO(dfs[4].to_csv(index=False)), skiprows=1, header=[0,1])
c = df1.iat[1,3]
print(c)
if (c == "Margaret"):
df1.to_csv("break.csv", mode='a', header=False)
print("Margaret found")
break
except:
if c:
print("waiting...")
c = False
continue
但是在这里,当值不可用时,它不会再试一次,而是自动跳到代码的下一部分,甚至不打印等待...".请建议我如何修改代码.我是编码初学者.因此,如果以简单的方式解释,将非常感激.TIA
But here, when the value is not available, instead of trying again, it automatically skips to next part of the code without even printing "waiting...". Please suggest how I can modify the code. I am a beginner in coding. So will be very thankful if it is explained in a simple manner. TIA
推荐答案
有些事情要做:
缩进中断,所以它在 if 内您一遍又一遍地读取相同的数据,因此删除 while 循环,因为您可能已经有一个更新数据的循环了.最终代码:
try:
df1 = pd.read_csv(io.StringIO(dfs[4].to_csv(index=False)), skiprows=1, header=[0,1])
c = df1.iat[1,3]
print(c)
if (c == "Margaret"):
df1.to_csv("break.csv", mode='a', header=False)
print("Margaret found")
break
except Exception as e:
print("waiting...")
continue
这篇关于虽然python中的真循环中断而不等待条件变为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论