【问题标题】:Remove duplicates from a list (in vim)从列表中删除重复项(在 vim 中)
【发布时间】:2011-10-01 15:09:54
【问题描述】:

这是我的清单:

['02', '03', '03', '16', '17', '17', '28', '29', '29']

我想知道如何从该列表中删除重复项。

当我将一个项目添加到列表中进行检查时是否也可以 如果该项目已经在列表中(以避免重复?)

【问题讨论】:

  • 你的问题不清楚。你的意思是删除vim中的重复行吗?
  • 对不起,不是来自 vimscript 中的数组

标签: list vim double duplicates


【解决方案1】:

试试

let list=['02', '03', '03', '16', '17', '17', '28', '29', '29']
let unduplist=filter(copy(list), 'index(list, v:val, v:key+1)==-1')

。第二个问题,见:h index()

顺便说一句,如果

  1. 所有列表项都是字符串;
  2. 不可能有空字符串;
  3. 您不关心列表项的顺序

那么您可能应该改用字典:对于大量字符串,搜索重复项会更快(实际上不需要)。

【讨论】:

    【解决方案2】:

    这种前模式(即在: 之后输入)正则表达式替换将消除重复项(前提是它们是连续的):

    s/\('[0-9]\+'\),\s\+\1/\1/g
    

    【讨论】:

    • 一定要喜欢 vim 及其所有细节
    【解决方案3】:

    Vim 7.4.218 (25 Mar 2014) and newer

    提供

    uniq({list} [, {func} [, {dict}]])          *uniq()* *E882*
            Remove second and succeeding copies of repeated adjacent
            {list} items in-place.  Returns {list}.  If you want a list
            to remain unmodified make a copy first: >
                :let newlist = uniq(copy(mylist))
    <       The default compare function uses the string representation of
            each item.  For the use of {func} and {dict} see |sort()|.
    

    【讨论】:

      【解决方案4】:

      您还可以将列表转换为字典中的键:

      let list=['02', '03', '03', '16', '17', '17', '28', '29', '29']
      let dict = {}
      for l in list
         let dict[l] = ''
      endfor
      let uniqueList = keys(dict)
      

      这适用于已排序和未排序的列表。

      【讨论】:

        猜你喜欢
        • 2014-09-30
        • 2021-04-02
        • 2016-01-28
        • 2011-01-13
        相关资源
        最近更新 更多