【问题标题】:Merging contents of two lists based on a if-loop基于 if 循环合并两个列表的内容
【发布时间】:2011-01-31 05:09:27
【问题描述】:

我在检查列表中的元素时遇到了一个小问题: 我有两个文件,内容是这样的

file 1:        file2:
 47            358 47
 48            450 49
 49            56 50

我将这两个文件解析成两个列表,并使用以下代码进行检查

for i in file_1:
   for j in file_2:
      j = j.split()
      if i == j[1]:
        x=' '.join(j)
        print >> write_in, x

如果 file_1 的值在 file_2 中不存在,我现在尝试获取“0”,例如,值“48”不存在 file_2,所以我需要得到类似的输出(中间只有一个空格这两个数字)而且这两个条件都应该只产生一个输出文件:

output_file:
  358 47
   0 48
  450 49
   56 50

我尝试使用字典方法,但我并没有完全得到我想要的(实际上我不知道如何在 python 中正确使用字典;))。任何帮助都会很棒。

【问题讨论】:

  • 你试过保留 else 语句吗?否则 x = '0'.join (j)
  • 数字(在文件 1 中和文件 2 中的第二个数字)总是按顺序排列吗?字母顺序还是数字顺序?他们甚至总是数字吗?输出文件是否需要按顺序排列?

标签: python list loops


【解决方案1】:
def file_process(filename1, filename2):

    # read first file with zeroes as values
    with open(filename1) as fp:
        adict= dict( (line.rstrip(), 0) for line in fp)

    # read second file as "value key"
    with open(filename2) as fp:
        adict.update(
            line.rstrip().partition(" ")[2::-2] # tricky, read notes
            for line in fp)
    for key in sorted(adict):
        yield adict[key], key

fp= open("output_file", "w")
fp.writelines("%s %s\n" % items for items in file_process("file1", "file2"))
fp.close()

str.partition(" ") 返回一个 (pre-space, space, post-space) 的元组。通过对元组进行切片,从项目 2(后空间)开始并移动 -2 步,我们返回一个(后空间,前空间)元组,它们是描述字典的(键,值)解决办法。

PS 嗯 :) 我刚刚注意到我的答案与 Daniel Stutzbach 的基本相同。

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    l1 = open('file1').read().split()
    l2 = [line.split() for line in open('file2')]
    
    for x, y in zip(l1, l2):
        if x not in y:
            print 0, x
        print ' '.join(y)
    

    但是如果你按照你的逻辑,输出应该是

    358 47
    0 48
    450 49
    0 49
    56 50
    

    而不是

    358 47
    0 48
    450 49
    56 50
    

    【讨论】:

      【解决方案3】:
      r1=open('file1').read().split()
      r2=open('file2').read().split()
      
      d=dict(zip(r2[1::2],r2[::2]))
      
      output='\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)
      
      open('output_file','wb').write(output)
      

      测试

      >>> file1='47\n48\n49\n50'
      >>> file2='358 47\n450 49\n56 50'
      >>>
      >>> r1=file1.split()
      >>> r2=file2.split()
      >>>
      >>> d=dict(zip(r2[1::2],r2[::2])) #
      >>> d
      {'47': '358', '50': '56', '49': '450'}
      >>>
      >>> print '\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)
      358 47
      0 48
      450 49
      56 50
      >>>
      

      【讨论】:

      • 文件对象没有 split() 方法。 open('file1').read().split() 也许吧?
      • file1 中没有50
      • @gnibbler,根据OP的输出文件和他的概念,有,如果50不存在,它应该在他的结果中显示0 50。
      【解决方案4】:

      这是一个使用字典的可读解决方案:

      d = {}
      for k in file1:
          d[k] = 0
      for line in file2:
          v, k = line.split()
          d[k] = v
      for k in sorted(d):
          print d[k], k
      

      【讨论】:

      • 使用.fromkeys classmethod 将字典初始化为特定值。
      【解决方案5】:

      你可以很容易地修改你的代码:

      for i in file_1:
          x = None
          for j in file_2:
              j = j.split()
              if i == j[1]:
                  x = ' '.join(j)
          if x is None:
              x = ' '.join(['0', i])
      

      根据您的输入,整个任务当然可能会进一步简化。目前,您的代码是0(n**2) 复杂度。

      【讨论】:

      • 其实是O(N+M)。您只需要对每个文件进行顺序扫描。
      猜你喜欢
      • 2021-12-07
      • 2021-06-26
      • 2011-12-20
      • 1970-01-01
      • 2021-03-04
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多