How to sort a dictionary items in vim

雨燕双飞 提交于 2021-01-29 15:39:09

问题


How to use sort function in vim script to sort a dictionary?. The help documentation doesn't seems to provide clear information on how a particular element in the dictionary can be sorted.

For eg: I am getting the quickfix items by calling getqflist(). How to sort this quickfix dictionary items with respect to line numbers?


回答1:


Define your comparison function, save result of the getqflist() to a variable and call sort(v, f)

Example:

function! LineLessThan(leftArg, rightArg)
  if a:leftArg['line'] == a:rightArg['line']
    return 0
  elseif a:leftArg['line'] < a:rightArg['line']
    return -1
  else
    return 1
  endif
endfunction

function! KeyLessThan(leftArg, rightArg)
  if a:leftArg['key'] ==# a:rightArg['key']
    return 0
  elseif a:leftArg['key'] <# a:rightArg['key']
    return -1
  else
    return 1
  endif
endfunction

let g:a = [{'line': 3, 'key': 'd'}, {'line': 1, 'key': 'e'}, {'line': 5, 'key': 'b'}, {'line': 2, 'key': 'a'}, {'line': 4, 'key': 'c'}]
call sort(g:a, function("LineLessThan"))
echo g:a
call sort(g:a, function("KeyLessThan"))
echo g:a


来源:https://stackoverflow.com/questions/63319382/how-to-sort-a-dictionary-items-in-vim

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!