如何将行转换为列表并读取其元素:Python

2024-03-28 17:11:24 发布

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

我正在从一个文件中读取如下内容: Ikard Wynne有限责任公司|[('209.163.183.92','209.163.183.95')]

    Innovation Technologies Ltd|[('91.238.88.0', '91.238.91.255'), ('195.128.153.0', '195.128.153.255')]
    House Of Flowers|[('69.15.170.220', '69.15.170.223'), ('108.178.223.20', '108.178.223.23')]
    Hertitage Peak Charter School|[('66.81.93.192', '66.81.93.207')]

我愿意将“|”后面的部分转换成一个列表,然后从列表中读取元组。我使用这个脚本来实现这一点,但是我希望脚本将每个列表识别为一个元素,而不是每个元组。有人知道怎么解决吗?你知道吗

for line in g:
    org= line.split("|")[0]
    ranges = [line.split('|')[1]]
    for range in ranges:
    print (range)

输出:

[('91.238.88.0', '91.238.91.255'), ('195.128.153.0', '195.128.153.255')]
[('69.15.170.220', '69.15.170.223'), ('108.178.223.20', '108.178.223.23')]
[('66.81.93.192', '66.81.93.207')]

        for ip in range:
        print (ip)

输出:

[
(
'
9
1
.
1
9
5
.
1
7
2
.
0
'
,

Tags: 文件inip脚本内容列表forline
1条回答
网友
1楼 · 发布于 2024-03-28 17:11:24

使用ast模块中的^{}

>>> import ast
>>> s = "Innovation Technologies Ltd|[('91.238.88.0', '91.238.91.255'), ('195.128.153.0', '195.128.153.255')]"
>>> z = ast.literal_eval(s.split('|')[1])
>>> z
[('91.238.88.0', '91.238.91.255'), ('195.128.153.0', '195.128.153.255')]
>>> z[0]
('91.238.88.0', '91.238.91.255')
>>> z[0][1]
'91.238.91.255'
>>> type(z)
<type 'list'>
>>> type(z[0])
<type 'tuple'>

根据文件:

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.

相关问题 更多 >