gpt4 book ai didi

python - 在 Python 中的 For 语句中为输入字段循环一个变量

转载 作者:太空宇宙 更新时间:2023-11-04 04:16:09 25 4
gpt4 key购买 nike

我想向用户显示另一个输入字段,但它不起作用,除非我在 new_url 的 For 循环中执行此操作 new_url = input("Please enter new URL for a screenshot (按返回停止):").strip() 但我想将输入字段移动到 For 循环之外的某个地方,所以我尝试对输入字段执行此操作,例如 new_url = new_url_input 并获取 new_url_input 变量并将其添加到我的代码中的其他位置,例如 new_url_input = input("Please enter new URL for a screenshot (press return to stop): ").strip( ) 但是当我这样做时,它只显示一次代码,但它应该像用户按下输入时那样工作,它显示另一个输入字段。请看这个question/answer有关我的主题的更多信息。

原始代码:

# Load the data
file_name = file_name = path/to/json/file
with open(file_name) as fh:
full_data = json.load(fh)

# Dig into the data to find the screenshots
screen_shots = full_data['tabs'][0]['views'][1]['screenshots']

# Loop over each screen shot, updating each one
for number, screen_shot in enumerate(screen_shots):
new_url = input("Please enter new URL (press return to stop): ").strip()

if new_url:
screen_shot.update({"url": new_url, "fullSizeURL": new_url})
else:
break

# Remove all entries which we did not update
screen_shots = screen_shots[:number]

# Save the data
with open(file_name, 'w') as fh:
json.dump(full_data, fh, indent=4)

我希望它如何工作/看起来的示例:

new_url_input = input("Please enter new URL (press return to stop): ").strip()

# Load the data
file_name = path/to/json/file
with open(file_name) as fh:
full_data = json.load(fh)

# Dig into the data to find the screenshots
screen_shots = full_data['tabs'][0]['views'][1]['screenshots']

# Loop over each screen shot, updating each one
for number, screen_shot in enumerate(screen_shots):
new_url = new_url_input

if new_url:
screen_shot.update({"url": new_url, "fullSizeURL": new_url})
else:
break

# Remove all entries which we did not update
screen_shots = screen_shots[:number]

# Save the data
with open(file_name, 'w') as fh:
json.dump(full_data, fh, indent=4)

最佳答案

当您调用 input() 时,它返回一个字符串,在循环中您只是将该字符串分配给一个新变量。您需要以某种方式再次调用 input() ,即使它是将其包装在一个函数中,例如使用 lambda 如下...

new_url_input = lambda: input("Please enter new URL (press return to stop): ").strip()

# ...other code...

for number, screen_shot in enumerate(screen_shots):
new_url = new_url_input()

编辑:现在我明白你在说什么(输入提示符上的说明有帮助),我认为这就是你想要做的......

new_url_inputs = []
input_prompt = 'Please enter new URL (press return to stop): '
new_url_input = input(input_prompt).strip()
while new_url_input:
new_url_inputs.append(new_url_input)
new_url_input = input(input_prompt).strip()

# ...other code...

for number, screen_short in enumerate(screen_shots):
new_url = new_url_inputs[number]
# ...etc...

关于python - 在 Python 中的 For 语句中为输入字段循环一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55386958/

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