Skip to main content
 首页 » 编程设计

Python 3.6之将不同类型的列表作为输入

2025年05月04日12cloudgamer

如果我有这样的输入:“1 2 3 4 5”,我可以将其转换为 int 列表,如下所示:

a = input("List: ") #"1 2 3 4 5" 
a = list(map(int, a.split()) 
print(a) #[1, 2, 3, 4, 5] 

如果我们有这样的输入:“1 2 hello 4 5.0”,可以将其转换为这样的列表:[1, 2, 'hello', 4, 5.0] ?

请您参考如下方法:

我为此使用了 ast.literal_eval。根据文档 literal_eval .

它安全地评估表达式节点或包含 Python 文字或容器显示的 Unicode 或 Latin-1 编码字符串。

import ast 
a="1 2 hello 4 5.0" 
 
def converter(l): 
    try: 
        return ast.literal_eval(l) 
    except ValueError: 
        return l 
 
print(list(map(converter,a.split()))) 

输入

1 2 hello 4 5.0 

输出

[1, 2, 'hello', 4, 5.0] 

输入

-123 123E123 

输出

[-123, 1.23e+125]