python数组形式inpu

2024-04-26 00:39:21 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,输入是[[1,2,3],[2,3,4]]形式

不像整数形式1 2 3 2 3 4

但是有[]

在代码中

input =[]
inputfunc() //get input array
print input

你输入

^{pr2}$

将打印python结果

^{pr2}$

我可以保存这个变量吗?或者我必须使用字符串解析?在


Tags: 字符串代码inputget整数array形式print
1条回答
网友
1楼 · 发布于 2024-04-26 00:39:21

可以使用^{}将该字符串转换为如下python对象:

>>> import ast
>>> ast.literal_eval('[[1,2,3],[2,3,4]]')
[[1, 2, 3], [2, 3, 4]]
>>> L=ast.literal_eval('[[1,2,3],[2,3,4]]')
>>> type(L)
<class 'list'>
>>> L
[[1, 2, 3], [2, 3, 4]]
>>>

ast代表抽象语法树。literal_eval()eval()安全得多。在

引用官方文件:

ast.literal_eval(node_or_string) Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

相关问题 更多 >