2

我想向用户显示另一个输入字段,但它不起作用,除非我在 For 循环中执行此操作,new_url new_url = input("Please enter new URL for a screenshot (press return to stop): ").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()但是当我这样做时,它只显示一次代码,但它应该像用户按下输入时一样工作,它会显示另一个输入字段。有关我的主题的更多信息,请参阅此问题/答案

原始代码:

# 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)
4

1 回答 1

1

当您调用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...
于 2019-03-27T21:53:02.313 回答