Python:如何读取列表格式的文件?

标签 python list dictionary

我有以下文件 (g)..

-verifiziert.com | [1401832800]
00.pm | [1418511600, 1418598000, 1418943600]
00.re | [1410213600, 1417906800, 1418425200, 1419116400, 1418770800, 1417993200]
-verifizierungen.ne | [1401832800]
0.mk | [1414796400, 1415919600, 1417129200, 1416783600]

我想把它放入 d[domains]=numbers 的字典中。对于列表中的每个数字,我想要一个整数,因为它目前是一个字符串。

我正在使用这段代码:

d = defaultdict(list)
for line in g:
    line = line.strip('\n')
    domain, bl_dates= line.split('|')
    bl_dates = [int(i) for i in bl_dates]
    d[domain].append(bl_dates)

但我收到此错误,似乎该列表未被识别为列表:

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    bl_dates = [int(i) for i in bl_dates]
ValueError: invalid literal for int() with base 10: '['

谁能帮我解决这个问题?

最佳答案

这种事情应该可行:

import json
d = defaultdict(list)
for line in g:
    domain, list = line.split('|')
    d[domain.strip()] = json.loads(list)

最后,d 看起来像这样:

{'00.re': [1410213600, 1417906800, 1418425200, 1419116400, 1418770800, 1417993200],
 '-verifizierungen.ne': [1401832800],
 '0.mk': [1414796400, 1415919600, 1417129200, 1416783600],
 '-verifiziert.com': [1401832800],
 '00.pm': [1418511600, 1418598000, 1418943600],
 }

关于Python:如何读取列表格式的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28406637/

相关文章:

使用 Plotly 客户端的 Python Dataframe 绘图

ruby-on-rails - 设计 - 列出用户

python - 在python的列表中连接元组的元素

python - 为什么 map 像 izip_longest with fill=None 一样工作?

python - 为什么Python使用全局变量而不是方法参数?

python - 统一码编码错误 : 'ascii' codec can't encode character u'\ufffd' in position 3: ordinal not in range(128)

python - 数据 API : ValueError: `y` argument is not supported when using dataset as input

python - 在 Matplotlib 中绘制列表

python - 填充 Python 字典

dictionary - 数组到 julia 中的元组