Pythonic方式对元组,字典项和转换为数组进行排序

时间:2016-04-18 00:13:58

标签: python sorting dictionary tuples

给定这个元组数组

{-# LANGUAGE StandaloneDeriving, UndecidableInstances, PatternSynonyms
  , TypeOperators, KindSignatures, PolyKinds, DataKinds, GADTs, TypeFamilies
  , MultiParamTypeClasses, FlexibleContexts, FlexibleInstances #-} 

data Variant = Primary | Unary | Mult | Add | Comp | Expr 

data ExprF (k :: Variant -> *) (x :: Variant) where 
  ID_F :: ExprF k 'Primary 
  Paren_F :: k 'Expr -> ExprF k 'Primary  
  Negate_F :: k 'Primary -> ExprF k 'Unary
  Mult_F :: k 'Mult -> k 'Unary -> ExprF k 'Mult 
  Add_F  :: k 'Add -> k 'Mult -> ExprF k 'Add 
  Comp_F :: k 'Add -> k 'Add -> ExprF k 'Comp 

data Expr' (x :: Variant) where 
  Expr' :: (x <= y) => Expr x -> Expr' y 

data Expr (x :: Variant) where 
  MkExpr :: ExprF Expr' x -> Expr x 

data ExprFlip (x :: Variant) where 
  MkExprFlip :: (x <= y) => ExprF ExprFlip x -> ExprFlip y 

pattern Id' = MkExprFlip ID_F 

data Nat = Z | S Nat 
infixr 0 $ 
type ($) f a = f a 

type family VariantIx (x :: Variant) :: Nat where 
  VariantIx 'Primary = 'Z 
  VariantIx 'Unary = 'S 'Z 
  VariantIx 'Mult = 'S $ 'S 'Z 
  VariantIx 'Add = 'S $ 'S $ 'S 'Z 
  VariantIx 'Comp = 'S $ 'S $ 'S $ 'S 'Z 
  VariantIx 'Expr = 'S $ 'S $ 'S $ 'S $ 'S 'Z 

data family (:<=:) (x :: k) (y :: k) 
class (<=) (x :: k) (y :: k) where 
  isLTEQ :: x :<=: y 

data instance (:<=:) (x :: Nat) y where 
  LT_Z :: 'Z :<=: n 
  LT_S :: n :<=: m -> 'S n :<=: 'S m 
instance 'Z <= n where isLTEQ = LT_Z 
instance (n <= m) => 'S n <= 'S m where isLTEQ = LT_S isLTEQ 

newtype instance (:<=:) (x :: Variant) y = IsSubtype (VariantIx x :<=: VariantIx y) 
instance (VariantIx x <= VariantIx y) => x <= y where isLTEQ = IsSubtype isLTEQ 

id_ = MkExpr ID_F 

pattern Id = MkExpr ID_F 

pattern Paren e = MkExpr (Paren_F (Expr' e)) 

pattern Neg e = MkExpr (Negate_F (Expr' e)) 

infixl 6 :+ 
pattern (:+) a b = MkExpr (Add_F (Expr' a) (Expr' b)) 

infixl 7 :* 
pattern (:*) a b = MkExpr (Mult_F (Expr' a) (Expr' b)) 

pattern Cmp a b = MkExpr (Comp_F (Expr' a) (Expr' b)) 

instance Show (Expr' x) where
  showsPrec k (Expr' x) = showsPrec k x  

instance Show (Expr x) where 
  showsPrec k (MkExpr x) = showsPrec k x 

deriving instance (Show (k 'Mult), Show (k 'Add), Show (k 'Expr), Show (k 'Primary), Show (k 'Unary)) => Show (ExprF k x) 

或者给这本词典

[('h1', 0.522611856461), ('h2', 0.438368797302), ('h3', 0.443703174591)]

如何创建按浮动项排序的'h'项{'h2': 0.438368797302, 'h3': 0.443703174591, 'h1': 0.522611856461} 数组?

1 个答案:

答案 0 :(得分:1)

列表:

v <- data.frame(id=1:3, a=1:3, b=c("Adam","John","Sam"),
     c=c("Smith","Bond","Ted"), d=c(10,15,20), stringsAsFactors=FALSE)