【问题标题】:Python: How iterate list to another list?Python:如何将列表迭代到另一个列表?
【发布时间】:2021-10-22 14:44:42
【问题描述】:

我应该得到合并的文本文件。我有一个 merge_txt 函数,它需要列表和文件名,但我得到了一个要合并的大文件列表。

我的大名单如下。它包含五个文件的路径,应该从 14 个不同的文件创建。

data = [
{'fn': '1_0001_01.txt', 'file': '0001.txt'},
{'fn': '1_0001_02.txt', 'file': '0001.txt'},
{'fn': '1_0001_03.txt', 'file': '0001.txt'},
{'fn': '1_0002_01.txt', 'file': '0002.txt'},
{'fn': '1_0002_02.txt', 'file': '0002.txt'},
{'fn': '1_0003_01.txt', 'file': '0003.txt'},
{'fn': '1_0003_02.txt', 'file': '0003.txt'},
{'fn': '1_0003_03.txt', 'file': '0003.txt'},
{'fn': '1_0004_01.txt', 'file': '0004.txt'},
{'fn': '1_0004_02.txt', 'file': '0004.txt'},
{'fn': '1_0004_03.txt', 'file': '0004.txt'}
{'fn': '1_0005_01.txt', 'file': '0005.txt'},
{'fn': '1_0005_02.txt', 'file': '0005.txt'},
{'fn': '1_0005_03.txt', 'file': '0005.txt'}
]

我试图了解如何迭代列表以获得新列表和文件名?

这样的列表应该被迭代。

lst = ['1_0001_01.txt', '1_0001_02.txt', '1_0001_03.txt']

这个列表应该交给merge_txt函数:

merge_txt(lst, '0001.txt')

有什么想法吗?我还没有想出任何解决方案。

【问题讨论】:

    标签: python python-3.x list append


    【解决方案1】:

    您可以使用 itertools 模块中的 groupby 根据字典中的 file 值对值进行分组。

    from itertools import groupby
    grouped = [list(g) for _, g in groupby(data, key=lambda x:x['file'])]
    

    分组后:

    for innerList in grouped:
        print([v['fn'] for v in innerList], innerList[0]['file'])
        
    ['1_0001_01.txt', '1_0001_02.txt', '1_0001_03.txt'] 0001.txt
    ['1_0002_01.txt', '1_0002_02.txt'] 0002.txt
    ['1_0003_01.txt', '1_0003_02.txt', '1_0003_03.txt'] 0003.txt
    ['1_0004_01.txt', '1_0004_02.txt', '1_0004_03.txt'] 0004.txt
    ['1_0005_01.txt', '1_0005_02.txt', '1_0005_03.txt'] 0005.txt
    

    现在,您可以将这些值传递给函数:

    for innerList in grouped:
        merge_txt([v['fn'] for v in innerList], innerList[0]['file'])
    

    您还可以通过直接迭代 groupby 对象来避免将 list(g) 存储在不必要地占用内存的单独列表中:

    for _,g in groupby(data, key=lambda x:x['file']):
        fns = [v['fn'] for v in g]
        # merge_txt(fns, _)
        print(fns, _)
    
    ['1_0001_01.txt', '1_0001_02.txt', '1_0001_03.txt'] 0001.txt
    ['1_0002_01.txt', '1_0002_02.txt'] 0002.txt
    ['1_0003_01.txt', '1_0003_02.txt', '1_0003_03.txt'] 0003.txt
    ['1_0004_01.txt', '1_0004_02.txt', '1_0004_03.txt'] 0004.txt
    ['1_0005_01.txt', '1_0005_02.txt', '1_0005_03.txt'] 0005.txt
    

    【讨论】:

      【解决方案2】:

      您只需将data 重新处理为另一种形式,其中每个文件(例如0001.txt)都与正确的其他文件列表相关联:

      from collections import defaultdict
      
      data = [
      {'fn': '1_0001_01.txt', 'file': '0001.txt'},
      {'fn': '1_0001_02.txt', 'file': '0001.txt'},
      {'fn': '1_0001_03.txt', 'file': '0001.txt'},
      {'fn': '1_0002_01.txt', 'file': '0002.txt'},
      {'fn': '1_0002_02.txt', 'file': '0002.txt'},
      {'fn': '1_0003_01.txt', 'file': '0003.txt'},
      {'fn': '1_0003_02.txt', 'file': '0003.txt'},
      {'fn': '1_0003_03.txt', 'file': '0003.txt'},
      {'fn': '1_0004_01.txt', 'file': '0004.txt'},
      {'fn': '1_0004_02.txt', 'file': '0004.txt'},
      {'fn': '1_0004_03.txt', 'file': '0004.txt'},
      {'fn': '1_0005_01.txt', 'file': '0005.txt'},
      {'fn': '1_0005_02.txt', 'file': '0005.txt'},
      {'fn': '1_0005_03.txt', 'file': '0005.txt'}
      ]
      
      data2 = defaultdict(list)
      for item in data:
          data2[item['file']].append(item['fn'])
      
      
      for k,lst in data2.items():
          merge_txt(lst, k)
      

      例如,上面对merge_txt() 的第一次调用将是: merge_txt(['1_0001_01.txt', '1_0001_02.txt', '1_0001_03.txt'], '0001.txt')

      【讨论】:

        【解决方案3】:

        通过简单的 for 循环,您可以在 Python 中迭代 list:

        lst = [x['fn'] for x in data]
        

        【讨论】:

          【解决方案4】:

          使用 pandas 的简单的一个班轮

          我们使用 pandas 形成一个数据表,其中 file 为一列,fn 为第二列。然后我们按file 值对表格行进行分组。分组后,我们将每个组合并/聚合到列表中。以文件名作为键的字典访问此结果

          import pandas as pd
          
          file_fn = pd.DataFrame(data=[
          {'fn': '1_0001_01.txt', 'file': '0001.txt'},
          {'fn': '1_0001_02.txt', 'file': '0001.txt'},
          {'fn': '1_0001_03.txt', 'file': '0001.txt'},
          {'fn': '1_0002_01.txt', 'file': '0002.txt'},
          {'fn': '1_0002_02.txt', 'file': '0002.txt'},
          {'fn': '1_0003_01.txt', 'file': '0003.txt'},
          {'fn': '1_0003_02.txt', 'file': '0003.txt'},
          {'fn': '1_0003_03.txt', 'file': '0003.txt'},
          {'fn': '1_0004_01.txt', 'file': '0004.txt'},
          {'fn': '1_0004_02.txt', 'file': '0004.txt'},
          {'fn': '1_0004_03.txt', 'file': '0004.txt'},
          {'fn': '1_0005_01.txt', 'file': '0005.txt'},
          {'fn': '1_0005_02.txt', 'file': '0005.txt'},
          {'fn': '1_0005_03.txt', 'file': '0005.txt'}
          ])
          
          d = df1.groupby('file')['fn'].agg(list).to_dict()
          print(d)
          
          {'0001.txt': ['1_0001_01.txt', '1_0001_02.txt', '1_0001_03.txt'],
           '0002.txt': ['1_0002_01.txt', '1_0002_02.txt'],
           '0003.txt': ['1_0003_01.txt', '1_0003_02.txt', '1_0003_03.txt'],
           '0004.txt': ['1_0004_01.txt', '1_0004_02.txt', '1_0004_03.txt'],
           '0005.txt': ['1_0005_01.txt', '1_0005_02.txt', '1_0005_03.txt']}
          

          只需通过 dict 键和值进行简单迭代即可。或者你也可以使用数据框应用

          df2 = df1.groupby('file')['fn'].agg(list)
          # method 1
          # df2['merged_txt'] = df2.apply(lambda x: merge_txt(x['fn'], x['file']))
          # method 2
          for file_, fn in df2.to_dict().items():
              merge_txt(fn, file_)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-08-09
            • 1970-01-01
            • 2017-05-07
            • 1970-01-01
            • 2020-03-30
            • 2021-04-04
            • 2019-10-18
            相关资源
            最近更新 更多