【问题标题】:Python program that generate a list from a given list according to a mapping根据映射从给定列表生成列表的 Python 程序
【发布时间】:2013-04-21 21:37:31
【问题描述】:

例如

组织列表:

aa b2 c d

映射:

aa 1
b2 2
d 3
c 4

gen_list:

1 2 4 3

实现这一点的 Python 方法是什么?假设 org_list 和映射在文件 org_list.txtmapping.txt 中,而 gen_list 将写入 gen_list.txt

顺便说一句,你认为哪种语言实现起来很简单?

【问题讨论】:

    标签: python list-comprehension data-munging


    【解决方案1】:

    只需使用list comprehension 循环遍历列表:

    gen_list = [mapping[i] for i in org_list]
    

    演示:

    >>> org_list = ['aa', 'b2', 'c', 'd']
    >>> mapping = {'aa': 1, 'b2': 2, 'd': 3, 'c': 4}
    >>> [mapping[i] for i in org_list]
    [1, 2, 4, 3]
    

    如果你在文件中有这些数据,首先在内存中建立映射:

    with open('mapping.txt') as mapfile:
        mapping = {}
        for line in mapfile:
            if line.strip():
                key, value = line.split(None, 1)
                mapping[key] = value
    

    然后从输入文件构建您的输出文件:

    with open('org_list.txt') as inputfile, open('gen_list.txt', 'w') as outputfile:
        for line in inputfile:
            try:
                outputfile.write(mapping[line.strip()] + '\n')
            except KeyError:
                pass  # entry not in the mapping
    

    【讨论】:

    • 不错的答案!我忘了提到文件的事情,现在问题更新了。
    • @JackWM:下次您可能需要提前指定。
    【解决方案2】:

    这里有适合您情况的解决方案。

    with open('org_list.txt', 'rt') as inp:
        lines = inp.read().split()
        org_list = map(int, lines)
    
    with open('mapping.txt', 'rt') as inp:
        lines = inp.readlines()
        mapping = dict(line.split() for line in lines)
    
    gen_list = (mapping[i] for i in org_list) # Or you may use `gen_list = map(mapping.get, org_list)` as suggested in another answers
    
    with open('gen_list.txt', 'wt') as out:
        out.write(' '.join(gen_list))
    

    我认为 Python 足够优雅地处理这种情况。

    【讨论】:

      【解决方案3】:

      另一种方式:

      In [1]: start = [1,2,3]
      In [2]: mapping = {1: "one", 2: "two", 3: "three"}
      In [3]: map(mapping.get, start)
      Out[3]: ['one', 'two', 'three']
      

      【讨论】:

      • 太棒了!如果 gen_list 预计是一个列表,则map(...) 应该在 Python 3 中被 list() 包裹。
      【解决方案4】:

      尝试使用 map() 或列表推导:

      >>> org_list = ['aa', 'b2', 'c', 'd']
      >>> mapping = {'aa': 1, 'b2': 2, 'd': 3, 'c': 4}
      
      >>> map(mapping.__getitem__, org_list)
      [1, 2, 4, 3]
      
      >>> [mapping[x] for x in org_list]
      [1, 2, 4, 3]
      

      【讨论】:

        【解决方案5】:
        mapping = dict(zip(org_list, range(1, 5)))       # change range(1, 5) to whatever
        gen_list = [mapping[elem] for elem in org_list]  # you want it to be
        

        【讨论】:

          猜你喜欢
          • 2022-07-22
          • 1970-01-01
          • 2011-04-27
          • 1970-01-01
          • 2016-12-09
          • 2012-08-14
          • 1970-01-01
          • 2020-10-29
          • 1970-01-01
          相关资源
          最近更新 更多