【问题标题】:Removing items from a list that appear in an external text file从出现在外部文本文件中的列表中删除项目
【发布时间】:2012-07-03 01:17:58
【问题描述】:

我正在尝试获取一个列表并将其与文本文件进行比较,从列表中删除出现在文本文件中的元素。

我的代码是:

baselist = open("testfile.txt", 'r')
twolist = ["one","two","three","four","five"]
for y in baselist:
    for x in range(0,len(twolist)):
        print("Working %s vs %s") % (twolist[x], y)
        if twolist[x] == y:
            print("Match!")
            remove.twolist[x]
baselist.close()

当我运行它时,我可以在输出中看到它正在比较“一”和“一”等,显然问题在于if twolist[x] == y:,但对于我的一生,我无法让它工作。我已经阅读和阅读并用谷歌搜索和搜索,但显然我错过了一些东西。有人能指出我正确的方向吗?

【问题讨论】:

    标签: python list comparison text-files


    【解决方案1】:
    • 打开文件通常最好使用with

    • 从文件中读取时,不会删除换行符;因此,例如,'two\n' != 'two' 并且您的比较测试失败。使用 .strip() 或 .rstrip() 删除空格,包括尾随换行符

    • for index in range(len(mylist)) 通常是一个坏信号;最好以for value in mylist 对列表进行操作并将其过滤为[value for value in mylist if test(value)]

    • 您的第一个 print 语句缩进错误

    • 您的remove 语法错误;应该是twolist.remove(x),并注意这只会删除第一次出现的x

    • 您的算法是 O(mn),其中 m 是 baselist 中的行数,n 是 twolist 中的行数;稍加注意,它可能是 O(m+n)。

    如果原始顺序很重要,

    with open('testfile.txt') as inf:
        twoset = set(twolist).difference(line.strip() for line in inf)
    
    twolist = [item for item in twolist if item in twoset]
    

    否则,

    with open('testfile.txt') as inf:
        twolist = list(set(twolist).difference(line.strip() for line in inf))
    

    【讨论】:

      【解决方案2】:

      你错过了rstrip()

      if twolist[x] == y.rstrip():
      

      并且在迭代列表时不要修改列表。

      更好地使用列表理解,并使用集合使其更快:

      $ cat 1.py 
      baselist = set([x.rstrip('\n') for x in open("testfile.txt", 'r')])
      twolist = ["one","two","three","four","five"]
      baselist = [x for x in twolist if x not in baselist]
      print baselist
      
      $ cat testfile.txt 
      one
      three
      
      $ python 1.py 
      ['two', 'four', 'five']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-27
        • 1970-01-01
        • 1970-01-01
        • 2017-02-25
        • 2016-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多