【问题标题】:Python: Store the data into two lists and then convert to a dictionaryPython:将数据存储到两个列表中,然后转换为字典
【发布时间】:2010-11-17 19:16:19
【问题描述】:

我是 python 新手,有一个关于在列表中存储列并将它们转换为字典的问题,如下所示:

我在下面显示的两列中有一个数据,带有节点(N)和边(E),我想首先制作这两列的列表,然后将这两个列表的字典制作为

{1:[9,2,10],2:[10,111,9],3:[166,175,7],4:[118,155,185]}

我该怎么做?谢谢。

N   E           
1   9       
1   2       
1   10      
2   10      
2   111     
2   9       
3   166     
3   175     
3   7       
4   118     
4   155     
4   185

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    defaultdictdict 的子类,这在这里很有用:

    import collections
    result=collections.defaultdict(list)
    for n,e in zip(N,E):
        result[n].append(e)
    

    【讨论】:

    • 上面显示的数据是一个文本文件而不是一个列表。你能告诉你的变量list 是什么吗?谢谢。
    • @Harpreet:假设您已经定义了NE 列表,我发布的代码可以按字面意思使用。 collections.defaultdict(list) 创建一个类似字典的对象,当 key 不在字典中时,result[key] 自动设置为等于空的 list
    • @Harpreet:文档 (docs.python.org/library/collections.html#defaultdict-examples) 中给出的示例与您的情况非常接近。如果你研究过这个例子,并且知道zip 是如何工作的(docs.python.org/library/functions.html#zip),那么你就会理解我的代码。
    • @Harpreet:list 是一个内置类型。 [1, 2, 8]list。调用时,list() 返回一个空列表:[]。每当使用不存在的键访问名为 resultdefaultdict 时,都会调用 list 以提供默认值(空列表)并将其添加到字典中。
    • @Steven Rumbalski:感谢您的补充说明。
    【解决方案2】:
    yourDict={}
    for line in file('r.txt', 'r'):
        k , v =  line.split()
        if k in yourDict.keys():
             yourDict[k].append(v)
        else:
             yourDict[k] = [v]
    
    print  yourDict
    

    输出: (你总是可以在最后删除 N:E)

    {'1': ['9', '2', '10'], '3': ['166', '175', '7'], '2': ['10', '111', '9'], '4': ['118', '155', '185'], 'N': ['E']}
    

    【讨论】:

    • @Harpreet:添加,如何处理文件
    【解决方案3】:

    以下内容在边缘上没有 for 循环。该迭代由 Python 使用内置方法在内部处理,对于大型图可能更快:

    import itertools
    import operator
    
    N = [ 1, 1, 1, 2, 2]
    E = [ 2, 3, 5, 4, 5]
    
    iter_g = itertools.groupby(zip(N,E), operator.itemgetter(0))
    
    dict_g = dict( (v, map(operator.itemgetter(1), n)) for v,n in iter_g )
    

    另外,如果你只需要一次数据,你可以只使用 iter_g 而不是构造字典。

    【讨论】:

      【解决方案4】:

      比 unutbu 的版本慢一点,但更短:)

      result = { }
      for n, e in ( line.split( ) for line in open( 'r.txt' ) ):
          result[ n ] = result.setdefault( n, [ ] ) + [ e ]
      

      【讨论】:

        【解决方案5】:

        这正是你想要的:

        import collections
        
        N = []
        E = []
        with open('edgelist.txt', 'r') as inputfile:
            inputfile.readline()  # skip header line
            for line in inputfile:
                n,e =  map(int,line.split())
                N.append(n)
                E.append(e)
        
        dct = collections.defaultdict(list)
        for n,e in zip(N,E):
            dct[n].append(e)
        dct = dict(dct)
        print dct
        # {1: [9, 2, 10], 2: [10, 111, 9], 3: [166, 175, 7], 4: [118, 155, 185]}
        

        【讨论】:

          【解决方案6】:

          以下是简短的回答:

          l1 = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
          l2 = [9, 2, 10, 10, 111, 9, 166, 175, 7, 118, 155,185]
          
          d = dict((i,[j for j,k in zip(l2,l1) if k == i]) for i in frozenset(l1))
          

          【讨论】:

          • 很抱歉用简短的答案狙击。但我无法抗拒。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-05
          • 1970-01-01
          • 2015-07-23
          相关资源
          最近更新 更多