You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中将输入词语转为URL列表仅生成最后一个元素的问题解决

问题修复:生成多个URL的列表

你的问题核心是循环中反复覆盖单个变量,而非收集所有生成的URL:

  • 每次循环时,URL变量都会被新的单个链接替换,循环结束后它仅保留最后一个词对应的链接
  • 最后执行URL.split(' ')自然只能得到包含最后一个URL的列表

修复后的代码(基础版)

search = input()

split_words = search.split(' ')
print(split_words)

url_list = []  # 初始化空列表用于存储所有URL
for word in split_words:  
    current_url = 'https://samplenotspamdotcom/' + word
    print(current_url)
    url_list.append(current_url)  # 将每个生成的URL添加到列表

print(url_list)

更简洁的写法(列表推导式)

如果想让代码更紧凑,可以用Python的列表推导式一步生成目标列表:

search = input()
url_list = [f'https://samplenotspamdotcom/{word}' for word in search.split(' ')]
print(url_list)

测试验证

当输入why not时,两种写法都会输出你期望的结果:

['https://samplenotspamdotcom/why', 'https://samplenotspamdotcom/not']

内容的提问来源于stack exchange,提问作者Wong_Urip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:55:22