解析字符串分组(Python)

2024-09-30 20:25:12 发布

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

我有一根像这样的绳子:

[["Name1","ID1","DDY1", "CALL1", "WHEN1"], ["Name2","ID2","DDY2", "CALL2", "WHEN2"],...];

这个字符串来自一个网站。可以有任意数量的分组。如何解析这个字符串并只打印每个分组的名称变量?在


Tags: 字符串名称数量网站id2name1id1绳子
2条回答
import ast
y = ast.literal_eval(input)
[x[0] for x in y]

感谢@stephan为我指出了正确的方向ast.literal_评估. 文件描述如下:

Safely evaluate an expression node or a string containing a Python expression. 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 expressions from untrusted sources without the need to parse the values oneself.

注意:这是Python2.6中的新功能。在

希望我能理解。在

>>> import json
>>> a = json.loads('[["Name1","ID1","DDY1", "CALL1", "WHEN1"], ["Name2","ID2","DDY2", "CALL2", "WHEN2"]]')
>>> [x[0] for x in a]
[u'Name1', u'Name2']
>>> 

相关问题 更多 >