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

如何在Python中通过单行代码获取列表输入

Python单行获取列表输入的方法

以下是几种适配不同输入格式的单行实现方案:

  • 获取以空格分隔的字符串列表:

    str_list = input().split()
    

    示例输入:apple banana cherry,输出结果:['apple', 'banana', 'cherry']

  • 获取以空格分隔的整数列表:

    int_list = list(map(int, input().split()))
    

    示例输入:1 2 3 4,输出结果:[1, 2, 3, 4]

  • 获取以逗号分隔的列表(输入如1,2,3或a,b,c):
    整数版本:

    int_list = list(map(int, input().split(',')))
    

    字符串版本:

    str_list = input().split(',')
    

如果之前尝试失败,大概率是代码里的分隔符和实际输入的分隔符不匹配,或者遗漏了类型转换步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:40:22