Python:如何改造Python列表并逐行打印?

2024-04-26 19:22:04 发布

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

我有一个这样的文件:

2.nseasy.com.|['azeaonline.com']
ns1.iwaay.net.|['alchemistrywork.com', 'dha-evolution.biz', 'hidada.net', 'sonifer.biz']
ns2.hd28.co.uk.|['networksound.co.uk']

预期结果:

^{pr2}$

当我尝试这样做时,我得到的是域的字符,而不是值域的项。这意味着dictionary d的值中的列表被识别为列表,但被识别为字符串。以下是我的代码:

^{3}$

当前结果示例:

w
o
o
d
l
a
n
d
f
a
r
m
e
r
s
m
a
r
k
e
t
.
o
r
g
'
]

Tags: 文件com列表netukcoevolutionbiz
3条回答

这是另一个(假设名称.txt包含您的数据):

with open('names.txt') as f: # Open the file for reading
  for line in f:             # iterate over each line
     host,parts=line.strip().split('|') # Split the parts on the |
     parts=parts.replace('[','').replace(']','') # Remove the [] chars
     parts_a=map(str.strip, parts.split(',')) # Split on the comma, and remove any spaces
     for part in parts_a:       # for the split part, iterate through each one
         print '{0}|{1}'.format(host, part)  # print the host and part separated by a |

注:您可以将第4行和第5行替换为零件_a=json.loads(parts)以及,假设|后面的部分是JSON。。。在

您不需要使用json在这种情况下,因为它不能解决您的问题,您可以在列表理解中使用^{}和{a2}来创建愿望对:

>>> from itertools import repeat
>>> import ast
>>> sp_l=[(i.split('|')[0],ast.literal_eval(i.split('|')[1])) for i in s.split('\n')]
>>> for k in [zip(repeat(i,len(j)),j) for i,j in sp_l]:
...    for item in k:
...         print '|'.join(item)
... 
2.nseasy.com.|azeaonline.com
ns1.iwaay.net.|alchemistrywork.com
ns1.iwaay.net.|dha-evolution.biz
ns1.iwaay.net.|hidada.net
ns1.iwaay.net.|sonifer.biz
ns2.hd28.co.uk.|networksound.co.uk

您使用json所做的是不正确的。s = json.dumps(domain_list)将列表转储到字符串sjson.loads(s)再次读取字符串,然后在字符串上设置范围并打印它,因此输出中只有单个字符。 尝试类似于:

d = defaultdict(list)
f = open(file,'r')
start = time()
for line in f:
    NS,domain_list = line.split('|')
    d[NS] = json.loads(domain_list.replace("'", '"'))


for NS, domains in d.items():
    for domain in domains:
        print (NS, domain)

相关问题 更多 >