问题
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