排序字符串和数字词典 [英] Sorting Dictionary of Strings and Numbers

查看:356
本文介绍了排序字符串和数字词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要进行排序的字典对象,但按键的形式为日期值

I have a dictionary object that needs to be sorted, but the keys are date values in the form


['Apr. 2013','May 2013','Feb. 2013',
'Mar. 2013','Jul. 2013','Aug. 2013',
'Sep. 2013','Oct. 2013','Jun. 2013','Nov. 2013']

正如你所看到的,日期是无序。相应的值,以每个键是一个数字。我想将它们按时间顺序进行排序。但是,由于月是字符串值,而且由于几个月没有按字母顺序按顺序,我不能只是自动对其进行排序。此外,虽然在code样品中未示出,可能存在多年不在2013为好。我怎么会去选本字典?

As you can see, the dates are out of order. The corresponding value to each key is a number. I want to sort them in chronological order. However, since the months are string values, and since months are not alphabetically in order, I cannot just sort them automatically. Also, though not shown in the code sample, there may be years that are not 2013 as well. How would I go about sorting this dictionary?

在此先感谢!

推荐答案

code从这里 被盗:

Code stolen from here:

  Const csSep = "|"
  Const cnMax = 100

  Dim sInp : sInp = "Apr. 2013|May. 2013|Apr. 2014|Feb. 2013|Apr. 2011|Mar. 2013|Jul. 2013|Aug. 2013"
  Dim aInp : aInp = Split(sInp, csSep) ' YourDic.Keys
  WScript.Echo "A:", vbCrLf & Join(aInp, vbCrLf)
  WScript.Echo "---------------------"

  Dim oNAL : Set oNAL = CreateObject( "System.Collections.ArrayList" )
  Dim oSB  : Set oSB  = CreateObject( "System.Text.StringBuilder" )
  Dim sWord
  For Each sWord In aInp
      Dim dtCmp : dtCmp = CDate(sWord) ' depends on regional/locale settings
      oSB.AppendFormat_3 "{0:yyyy-MM}{1}{2}", dtCmp, csSep, sWord
      sWord = oSB.ToString()
      oSB.Length = 0
      oNAL.Add sWord
  Next
  oNAL.Sort

  ReDim aOut(oNAL.Count - 1)
  Dim i
  For i = 0 To UBound(aOut)
      aOut(i) = Split(oNAL(i), csSep)(1)
  Next
  WScript.Echo "B:", vbCrLf & Join(aOut, vbCrLf)

输出:

A:
Apr. 2013
May. 2013
Apr. 2014
Feb. 2013
Apr. 2011
Mar. 2013
Jul. 2013
Aug. 2013
---------------------
B:
Apr. 2011
Feb. 2013
Mar. 2013
Apr. 2013
May. 2013
Jul. 2013
Aug. 2013
Apr. 2014

的理论是(C)R. L.施瓦茨(见的Schwartzian变换)。

更新WRT玛莎的回答(和我的警告):

不必太多信心VBScript的日期的转换:

Don't have to much confidence in VBScript's date conversions:

>> WScript.Echo CDate("Dez 2013")
>>
Error Number:       13  ' <-- can't read german
Error Description:  Type mismatch

>> WScript.Echo CDate("Dec 2013") ' <-- can read english
>>
01.12.2013 ' <-- can write german

>> WScript.Echo DateValue("Dez 2013")
>>
Error Number:       13 ' <-- DateValue isn't more intelligent
Error Description:  Type mismatch

这篇关于排序字符串和数字词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆