从列表中删除重复项(在vim中)

时间:2011-07-08 21:44:20

标签: list vim double duplicates

这是我的清单:

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

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

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

4 个答案:

答案 0 :(得分:14)

尝试

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. 您不关心列表项的顺序
  4. 那么你应该使用一个词典代替:对于大量搜索重复项的字符串来说更快(而且实际上不是必需的)。

答案 1 :(得分:4)

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

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

答案 2 :(得分:3)

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

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)

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

答案 3 :(得分:1)

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()|.