【问题标题】:Convert this file into dictionary将此文件转换为字典
【发布时间】:2015-04-07 15:26:25
【问题描述】:

我在 Stackoverflow 上环顾四周,但可以但找不到这里讨论的内容。我有一个要转换成字典的列表。

3
banana
apple
orange
5.00E-2
1
7.02E-4
1.00E-4
4
5.13E-4
-5.76E-2
8
7.23E-8
-6.12E-9
4
5.02E

数字 3 是键的数量。接下来的 3 个字符串是键名。接下来的 3 个值是列表的第一个元素....等等。例如我会得到:

  mydict['banana']=[ 5.00E-2, 1.00E-4, -5.76E-2, -6.12E-9]
  mydict['apple'] =[1,           4,       8,        4]
  mydict['orange']=[ 7.02E-4, 5.13E-4,  7.23E-8,   np.nan ]

请注意,最后一个元素并不完整,只是“5.02E”,必须用 numpy.nan 替换。此外,每个列表中的元素数量必须相同,缺失值应为 numpy.nan。这是一个 python 2.7.x 的问题。

所以我的问题是我正在寻找创建字典的最佳方式。怎么做?

【问题讨论】:

    标签: python python-2.7 numpy dictionary


    【解决方案1】:
    num = mylist[0]
    mydict = {}
    for i in range(num):
        mydict[mylist[i + 1]] = mylist[i + 1 + num::num]
    

    或者如果你更喜欢单行,

    mydict = {mylist[i + 1]:mylist[num + i + 1::num] for i in range(mylist[0])}
    

    请注意,这不会用numpy.nan 替换缺失的项目;就像

    from itertools import izip_longest
    import numpy as np
    
    num      = mylist[0]
    labels   = mylist[1:num + 1]
    num_cols = (len(mylist) - 2) // num
    cols     = (mylist[1 + c*num::num] for c in range(1, num_cols + 2))
    rows     = izip_longest(*cols, fillvalue=np.nan)
    
    mydict = dict(zip(labels, rows))
    

    【讨论】:

    • @no_name 我喜欢你的想法。你能详细介绍一下吗?
    • 第一个 'num' 值是键名。你的答案不会创建一个字典吗?
    • @CorruptedStack,听写理解的想法是在上面的答案中实现的,我认为这个答案适用于你的代码......不是吗?
    • @no_name 我想你正在编辑答案,因为我正在阅读它哈哈哈
    • 您的一个班轮比使用 itertools 的结果做得更好。但我想我必须在你完成之前测试过你的答案
    【解决方案2】:

    我认为,itertools.cycle + izip 可能在这里有用:

    from collections import defaultdict
    from itertools import cycle, izip, count, repeat
    
    result = defaultdict(list)
    
    with open(path) as fp:
        num = int(next(fp))
        idx = 0
    
        # create infinite loop of repeating keys to match them with the values:
        keys = cycle([next(fp).strip() for _ in range(num)])
    
        for k, v, c in izip(keys, fp, count()):
            result[k].append(np.float(v))
    
        if (c + 1) % num: # need to populate with nans
            result[k].extend(repeat(np.nan, num - (c + 1) % num))
    

    【讨论】:

    • 你的意思是缩进最后一个 if 语句。是还是不是?
    • @CorruptedStack 按我的意思缩进,for-loop 完成后,我们可能需要完成最后一个键的列表。
    • 我试图测试你的代码。我遇到了“keys = cycle(next(f).strip() for f in range(num))”的问题。那行有错别字吗?我收到错误“TypeError:int object is not an iterator”
    • @CorruptedStack 我修好了那条线,抱歉。循环也应该在[ ] 以消除懒惰。
    • @CorruptedStack 也就是说,上面的单行是一个更好的解决方案:)
    猜你喜欢
    • 1970-01-01
    • 2011-03-06
    • 2017-11-19
    • 1970-01-01
    • 2017-03-27
    • 2017-11-08
    相关资源
    最近更新 更多