超出范围的为长整型,点击源码上的复制按键还

作者: 编程  发布:2019-11-20

9159.com 19159.com 2

1.angular.bind()

Python数据类型及其方法详解

我们在学习编程语言的时候,都会遇到数据类型,这种看着很基础也不显眼的东西,却是很重要,本文介绍了python的数据类型,并就每种数据类型的方法作出了详细的描述,可供知识回顾。

9159.com 3

  1 /*2048*/
  2 
  3 #include<stdio.h>
  4 #include<stdlib.h>
  5 #include<conio.h>
  6 #include<time.h>
  7 
  8 void print(void);/*显示游戏界面*/
  9 int add(void);/*对中间变量数组进行处理*/
 10 
 11 int code[4][4] =
 12    {
 13     {0,0,0,0},
 14     {0,0,0,0},
 15     {0,0,0,0},
 16     {0,0,0,0},
 17    };/*游戏中的16个格子*/
 18 int temp[5];/*中间变量*/
 19 int move = 0;/*移动次数*/
 20 int score = 0;/*分数*/
 21 
 22 
 23 
 24 int main(void)
 25 {
 26      int gameover = 0;/*判断游戏是否结束,1结束,0继续*/
 27      int i,j;
 28      int change = 1;/*判断格子中的数是否改变,0不变*/
 29      char input;
 30      srand((unsigned)time(NULL));/*设置随机数的起点*/
 31      while(gameover == 0)
 32          {
 33               if(change >= 1)/*仅当数发生改变时添加新数*/
 34                {
 35                     do
 36                      {
 37                           i=((unsigned)rand()) % 4;
 38                           j=((unsigned)rand()) % 4;
 39                      }while(code[i][j] != 0);
 40                     if(((unsigned)rand()) % 4 == 0)
 41                      {
 42                           code[i][j]=4;
 43                      }
 44                     else
 45                      {
 46                           code[i][j]=2;/*随机选一个空格填上2或4*/
 47                      }
 48                     move++;/*增加次数*/
 49                }
 50               print();/*显示*/
 51               input = getch();/*输入方向*/
 52               change = 0;
 53               switch(input)
 54                    {
 55                         case '0':/*退出*/
 56                                  printf("Are you sure to exit?(y/n)");
 57                                  input=getchar();
 58                                  if(input=='y'||input=='Y')
 59                                     exit(0);
 60                                  break;
 61 
 62                         case 'W':
 63 
 64                         case 'w':/*上*/
 65                                  for(j=0;j<=3;j++)
 66                                    {
 67                                         for(i=0;i<=3;i++)
 68                                           {
 69                                                temp[i]=code[i][j];/*把一列数移到中间变量*/
 70                                           }
 71                                         temp[4]=0;
 72                                         change += add();
 73                                         for(i=0;i<=3;i++)
 74                                           {
 75                                                code[i][j]=temp[i];/*把处理好的中间变量移回来*/
 76                                           }
 77                                     }
 78                                   break;
 79 
 80                         case 'A':
 81 
 82                         case 'a':/*左*/
 83                                  for(i=0;i<=3;i++)
 84                                    {
 85                                         for(j=0;j<=3;j++)
 86                                           {
 87                                                temp[j]=code[i][j];/*把一行数移到中间变量*/
 88                                           }
 89                                         temp[4]=0;
 90                                         change += add();
 91                                         for(j=0;j<=3;j++)
 92                                           {
 93                                                code[i][j]=temp[j];/*把处理好的中间变量移回来*/
 94                                           }
 95                                    }
 96                                  break;
 97 
 98                         case 'S':
 99 
100                         case 's':/*下*/
101                                  for(j=0;j<=3;j++)
102                                    {
103                                         for(i=0;i<=3;i++)
104                                           {
105                                                temp[i]=code[3-i][j];/*把一列数移到中间变量*/
106                                           }
107                                         temp[4]=0;
108                                         change += add();
109                                         for(i=0;i<=3;i++)
110                                           {
111                                                code[3-i][j]=temp[i];/*把处理好的中间变量移回来*/
112                                           }
113                                    }
114                                  break;
115 
116                         case 'D':
117 
118                         case 'd':/*右*/
119                                  for(i=0;i<=3;i++)
120                                    {
121                                         for(j=0;j<=3;j++)
122                                           {
123                                                temp[j]=code[i][3-j];/*把一行数移到中间变量*/
124                                           }
125                                         temp[4]=0;
126                                         change += add();
127                                         for(j=0;j<=3;j++)
128                                           {
129                                                code[i][3-j]=temp[j];/*把处理好的中间变量移回来*/
130                                           }
131                                    }
132                                  break;
133                    }
134               gameover=1;
135               for(i=0;i<=3;i++)
136               for(j=0;j<=3;j++)
137               if(code[i][j]==0)
138               gameover=0;/*所有格子都填满则游戏结束*/
139         }
140     printf("Game over!n");
141     getch();
142 
143     return 0;
144 }
145 
146 void print(void)/*显示游戏界面*/
147 {
148     int i,j;
149     system("CLS");/*清屏*/
150     printf("2048n");
151     printf("W--UP A--LEFT S--DOWN D--RIGHT 0--EXITn");
152     printf("Score:%d Move:%dn",score,move);
153     printf("Made by lanshanxiaon");
154     printf("|-----------------------|n");/*显示横向分隔线*/
155     for(i=0;i<=3;i++)
156        {
157            for(j=0;j<=3;j++)
158               {
159                    if(code[i][j]==0)
160                      {
161                           printf("|     ");/*0显示空格*/
162                      }
163                    else
164                      {
165                           printf("|%5d",code[i][j]);/*显示数字和分隔线*/
166                      }
167               }
168            printf("|n|-----------------------|n");/*显示横向分隔线*/
169        }
170 }
171 
172 int add(void)/*对中间变量数组进行处理*/
173 {
174     int i;
175     int t=0;
176     int change=0;/*判断数组是否有改变,0不变,1变化*/
177     do
178      {
179           for(i=0;i<=3;i++)
180             {
181                  if(temp[i]==0)
182                   {
183                        if(temp[i]!=temp[i+1])
184                          change=1;/*当一个0后面不是0时数组改变*/
185                        temp[i]=temp[i+1];
186                        temp[i+1]=0;
187                   }
188             }/*去掉中间的0*/
189           t++;
190      }while(t<=3);/*重复多次*/
191     for(i=1;i<=3;i++)
192         {
193              if(temp[i]==temp[i-1])
194               {
195                    if(temp[i]!=0)
196                      {
197                           change=1;/*当两个非零相同的数相加时数组改变*/
198                           score=score+temp[i];/*加分*/
199                      }
200                    temp[i-1]=temp[i-1]*2;
201                    temp[i]=0;
202               }
203         }/*把两个相邻的相同的数加起来*/
204 
205     return change;
206 }

9159.com 49159.com 5

一、整型和长整型

整型:数据是不包含小数部分的数值型数据,比如我们所说的1、2、3、4、122,其type为"int"

长整型:也是一种数字型数据,但是一般数字很大,其type为"long"

在python2中区分整型和长整型,在32位的机器上,取值范围是-2147483648~2147483647,超出范围的为长整型,在64位的机器上,取值范围为-9223372036854775808~9223372036854775807(通常也与python的解释器的位数有关)。

在python3中,不存在整型和长整型之分,只有整型。

举个例子:

9159.com 69159.com 7

python2中
number = 123
print (type(number))
number2 = 2147483647
print (type(number2))
number2 = 2147483648    #我们会看到超过2147483647这个范围,在py2中整形就会变成长整形了
print (type(number2))
#运行结果
<type 'int'>
<type 'int'>
<type 'long'>
#python3中
number = 123
print (type(number))
number2 = 2147483648   
print (type(number2))    #在python3中并不会
#运行结果
<class 'int'>
<class 'int'>

View Code

常用的method的如下:

.bit_length()

取最短bit位数

9159.com 89159.com 9

  def bit_length(self): # real signature unknown; restored from __doc__
        """
        int.bit_length() -> int

        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        6
        """
        return 0

View Code

举个例子:

9159.com 109159.com 11

number = 12  #1100 
print(number.bit_length())
#运行结果
4

View Code

 

原型模式就是从一个对象在创建另外一个对象,不需要知道任何创建的细节:(克隆)

View Code

<!DOCTYPE HTML>
<html ng-app>
<head>
</head>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</body>
<script>
  /*  angluar.bind(obj,fn,[args]) 把对象绑定到函数里,生成新的函数  */
    var obj={name:'xiaoming'};
    var fn= function (arg) {
        console.log(this.name+' is '+arg);  // this 指 obj
    }
    var f1=angular.bind(obj,fn,'so handsome'); // 参数可选
    f1();
    var f2=angular.bind(obj,fn);          // 可在最后才传参数
    f2('weak!');
</script>
</body>
</html>

 二、浮点型

 浮点型可以看成就是小数,type为float。

9159.com 129159.com 13

#浮点型
number = 1.1
print(type(number))
#运行结果
<class 'float'>

View Code

 常用method的如下:

.as_integer_ratio()

返回元组(X,Y),number = k ,number.as_integer_ratio() ==>(x,y) x/y=k

9159.com 149159.com 15

    def as_integer_ratio(self): # real signature unknown; restored from __doc__
        """
        float.as_integer_ratio() -> (int, int)

        Return a pair of integers, whose ratio is exactly equal to the original
        float and with a positive denominator.
        Raise OverflowError on infinities and a ValueError on NaNs.

        >>> (10.0).as_integer_ratio()
        (10, 1)
        >>> (0.0).as_integer_ratio()
        (0, 1)
        >>> (-.25).as_integer_ratio()
        (-1, 4)
        """
        pass

View Code

 举个例子

9159.com 169159.com 17

number = 0.25
print(number.as_integer_ratio())
#运行结果
(1, 4)

View Code

.hex()

 以十六进制表示浮点数

9159.com 189159.com 19

    def hex(self): # real signature unknown; restored from __doc__
        """
        float.hex() -> string

        Return a hexadecimal representation of a floating-point number.
        >>> (-0.1).hex()
        '-0x1.999999999999ap-4'
        >>> 3.14159.hex()
        '0x1.921f9f01b866ep+1'
        """
        return ""

View Code

 举个例子

9159.com 209159.com 21

number = 3.1415
print(number.hex())
#运行结果
0x1.921cac083126fp+1

View Code

.fromhex()

将十六进制小数以字符串输入,返回十进制小数

9159.com 229159.com 23

    def fromhex(string): # real signature unknown; restored from __doc__
        """
        float.fromhex(string) -> float

        Create a floating-point number from a hexadecimal string.
        >>> float.fromhex('0x1.ffffp10')
        2047.984375
        >>> float.fromhex('-0x1p-1074')
        -5e-324
        """

View Code

举个例子

9159.com 249159.com 25

print(float.fromhex('0x1.921cac083126fp+1'))
#运行结果
3.1415

View Code

.is_integer()

判断小数是不是整数,比如3.0为一个整数,而3.1不是,返回布尔值

9159.com 269159.com 27

    def is_integer(self, *args, **kwargs): # real signature unknown
        """ Return True if the float is an integer. """
        pass

View Code

举个例子

9159.com 289159.com 29

number = 3.1415
number2 = 3.0
print(number.is_integer())
print(number2.is_integer())
#运行结果
False
True

View Code

 

以创建简历为例:

2048小游戏代码在上面的View Code中,将加号展开就可以看到。

View Code

三、字符类型

字符串就是一些列的字符,在Python中用单引号或者双引号括起来,多行可以用三引号。

9159.com 309159.com 31

name = 'my name is Frank'
name1 = "my name is Frank"
name2 = '''my name is Frank
I'm 23 years old,      
       '''
print(name)
print(name1)
print(name2)
#运行结果
my name is Frank
my name is Frank
my name is Frank
I'm 23 years old  

View Code

常用method的如下:

.capitalize()

字符串首字符大写

9159.com 329159.com 33

  def capitalize(self): # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str

        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""

View Code

举个例子

9159.com 349159.com 35

name = 'my name is Frank'
#运行结果
My name is frank

View Code

.center()

字符居中,指定宽度和填充字符(默认为空格)

9159.com 369159.com 37

  def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str

        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

View Code

举个例子

9159.com 389159.com 39

flag = "Welcome Frank"
print(flag.center(50,'*'))
#运行结果
******************Welcome Frank*******************

View Code

.count()

计算字符串中某个字符的个数,可以指定索引范围

9159.com 409159.com 41

    def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int

        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0

View Code

举个例子

9159.com 429159.com 43

flag = 'aaababbcccaddadaddd'
print(flag.count('a'))
print(flag.count('a',0,3))
#运行结果
7
3

View Code

9159.com,.encode()

编码,在python3中,str默认是unicode数据类型,可以将其编码成bytes数据

9159.com 449159.com 45

    def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes

        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""

View Code

举个例子

9159.com 469159.com 47

flag = 'aaababbcccaddadaddd'
print(flag.encode('utf8'))
#运行结果
b'aaababbcccaddadaddd'

View Code

.endswith()

判断字符串结尾是否是某个字符串和字符,可以通过索引指定范围

9159.com 489159.com 49

   def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool

        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

View Code

举个例子

9159.com 509159.com 51

flag = 'aaababbcccaddadaddd'
print(flag.endswith('aa'))
print(flag.endswith('ddd'))
print(flag.endswith('dddd'))
print(flag.endswith('aaa',0,3))
print(flag.endswith('aaa',0,2))
#运行结果
False
True
False
True
False

View Code

.expandtabs()

把制表符tab("t")转换为空格

9159.com 529159.com 53

  def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str

        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""

View Code

举个例子

9159.com 549159.com 55

flag = "thello python!"
print(flag)
print(flag.expandtabs())   #默认tabsize=8
print(flag.expandtabs(20))
#运行结果
    hello python!             #一个tab,长度为4个空格
        hello python!         #8个空格
                    hello python!    #20个空格

View Code

.find()

查找字符,返回索引值,可以通过指定索引范围内查找,查找不到返回-1

9159.com 569159.com 57

    def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int

        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

View Code

举个例子

9159.com 589159.com 59

flag = "hello python!"
print(flag.find('e'))
print(flag.find('a'))
print(flag.find('h',4,-1))
#运行结果
1
-1
9

View Code

.format()

格式化输出,使用"{}"符号作为操作符。

9159.com 609159.com 61

def format(self, *args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str

        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

View Code

举个例子

9159.com 629159.com 63

#位置参数
flag = "hello {0} and {1}!"
print(flag.format('python','php'))
flag = "hello {} and {}!"
print(flag.format('python','php'))
#变量参数
flag = "{name} is {age} years old!"
print(flag.format(name='Frank',age = 23))
#结合列表
infor=["Frank",23]
print("{0[0]} is {0[1]} years old".format(infor))
#运行结果
hello python and php!
hello python and php!
Frank is 23 years old!
Frank is 23 years old

View Code

.format_map()

格式化输出

9159.com 649159.com 65

 def format_map(self, mapping): # real signature unknown; restored from __doc__
        """
        S.format_map(mapping) -> str

        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""

View Code

举个例子

9159.com 669159.com 67

people={
    'name':['Frank','Caroline'],
    'age':['23','22'],
}
print("My name is {name[0]},i am {age[1]} years old !".format_map(people))
#运行结果
My name is Frank,i am 22 years old !

View Code

.index()

根据字符查找索引值,可以指定索引范围查找,查找不到会报错

9159.com 689159.com 69

 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int

        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

View Code

举个例子

9159.com 709159.com 71

flag = "hello python!"
print(flag.index("e"))
print(flag.index("o",6,-1))
#运行结果
1
10

View Code

.isalnum()

判断是否是字母或数字组合,返回布尔值

9159.com 729159.com 73

def isalnum(self): # real signature unknown; restored from __doc__
        """
        S.isalnum() -> bool

        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例子

9159.com 749159.com 75

flag = "hellopython"
flag1 = "hellopython22"
flag2 = "hellopython!!"
flag3 = "!@#!#@!!@"
print(flag.isalnum())
print(flag1.isalnum())
print(flag2.isalnum())
print(flag3.isalnum())
#运行结果
True
True
False
False

View Code

.isalpha()

判断是否是字母组合,返回布尔值

9159.com 769159.com 77

 def isalpha(self): # real signature unknown; restored from __doc__
        """
        S.isalpha() -> bool

        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例子

9159.com 789159.com 79

flag = "hellopython"
flag1 = "hellopython22"
print(flag.isalpha())
print(flag1.isalpha())
#运行结果
True
False

View Code

.isdecimal()

判断是否是一个十进制正整数,返回布尔值

9159.com 809159.com 81

  def isdecimal(self): # real signature unknown; restored from __doc__
        """
        S.isdecimal() -> bool

        Return True if there are only decimal characters in S,
        False otherwise.
        """
        return False

View Code

举个例子

9159.com 829159.com 83

number = "1.2"
number1 = "12"
number2 = "-12"
number3 = "1222"
print(number.isdecimal())
print(number1.isdecimal())
print(number2.isdecimal())
print(number3.isdecimal())
#运行结果
False
True
False
True

View Code

isdigit()

判断是否是一个正整数,返回布尔值,与上面isdecimal类似

9159.com 849159.com 85

  def isdigit(self): # real signature unknown; restored from __doc__
        """
        S.isdigit() -> bool

        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例子

9159.com 869159.com 87

number = "1.2"
number1 = "12"
number2 = "-12"
number3 = "11"
print(number.isdigit())
print(number1.isdigit())
print(number2.isdigit())
print(number3.isdigit())
#运行结果
False
True
False
True

View Code

.isidentifier()

判断是否为python中的标识符

9159.com 889159.com 89

 def isidentifier(self): # real signature unknown; restored from __doc__
        """
        S.isidentifier() -> bool

        Return True if S is a valid identifier according
        to the language definition.

        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False

View Code

举个例子

9159.com 909159.com 91

flag = "cisco"
flag1 = "1cisco"
flag2 = "print"
print(flag.isidentifier())
print(flag1.isidentifier())
print(flag2.isidentifier())
#运行结果
True
False
True

View Code

.islower()

 判断字符串中的字母是不是都是小写,返回布尔值

9159.com 929159.com 93

    def islower(self): # real signature unknown; restored from __doc__
        """
        S.islower() -> bool

        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

View Code

举个例子

9159.com 949159.com 95

flag = "cisco"
flag1 = "cisco222"
flag2 = "Cisco"
print(flag.islower())
print(flag1.islower())
print(flag2.islower())
#运行结果
True
True
False

View Code

.isnumeric()

判断是否为数字,这个很强大,中文字符,繁体字数字都可以识别

9159.com 969159.com 97

 def isnumeric(self): # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool

        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False

View Code

举个例子

9159.com 989159.com 99

number = "123"
number1 = "一"
number2 = "壹"
number3 = "123q"
number4 = "1.1"
print(number.isnumeric())
print(number1.isnumeric())
print(number2.isnumeric())
print(number3.isnumeric())
print(number4.isnumeric())
#运行结果
True
True
True
False
False

View Code

.isprintable()

判断引号里面的是否都是可打印的,返回布尔值

9159.com 1009159.com 101

   def isprintable(self): # real signature unknown; restored from __doc__
        """
        S.isprintable() -> bool

        Return True if all characters in S are considered
        printable in repr() or S is empty, False otherwise.
        """
        return False

View Code

举个例子

9159.com 1029159.com 103

flag = "n123"
flag1 = "t"
flag2 = "123"
flag3 = r"n123"    # r 可以是转义字符失效
print(flag.isprintable())     #n不可打印
print(flag1.isprintable())    #t不可打印
print(flag2.isprintable())
print(flag3.isprintable())
#运行结果
False
False
True
True

View Code

.isspace()

判断字符串里面都是空白位,空格或者tab,返回布尔值

9159.com 1049159.com 105

  def isspace(self): # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool

        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例子

9159.com 1069159.com 107

flag = '    '     #4个空格
flag1 = '        '#2个tab
print(flag.isspace())
print(flag1.isspace())
#运行结果
True
True

View Code

.istitle()

判断字符串里面的字符是否都是大写开头,返回布尔值

9159.com 1089159.com 109

  def isspace(self): # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool

        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

View Code

举个例子

9159.com 1109159.com 111

flag = "Welcome Frank"
flag1 = "Welcome frank"
print(flag.istitle())
print(flag1.istitle())
#运行结果
True
False

View Code

.isupper()

判断是否都是字符串里的字母都是大写

9159.com 1129159.com 113

    def isupper(self): # real signature unknown; restored from __doc__
        """
        S.isupper() -> bool

        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

View Code

举个例子

9159.com 1149159.com 115

flag = "WELCOME1"
flag1 = "Welcome1"
print(flag.isupper())
print(flag1.isupper())
#运行结果
True
False

View Code

.join()

将字符串以指定的字符连接生成一个新的字符串

9159.com 1169159.com 117

  def join(self, iterable): # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str

        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""

View Code

举个例子

9159.com 1189159.com 119

flag = "welcome"
print("#".join(flag))
#运行结果
w#e#l#c#o#m#e

View Code

.ljust()

左对齐,可指定字符宽度和填充字符

9159.com 1209159.com 121

   def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.ljust(width[, fillchar]) -> str

        Return S left-justified in a Unicode string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

View Code

举个例子

9159.com 1229159.com 123

flag = "welcome"
print(flag.ljust(20,"*"))
#运行结果
welcome*************

View Code

.rjust()

右对齐,可指定字符宽度和填充字符

9159.com 1249159.com 125

    def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.rjust(width[, fillchar]) -> str

        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

View Code

举个例子

9159.com 1269159.com 127

flag = "welcome"
print(flag.rjust(20,"*"))
#运行结果
*************welcome

View Code

.lower()

对字符串里的所有字母转小写

9159.com 1289159.com 129

    def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str

        Return a copy of the string S converted to lowercase.
        """
        return ""

View Code

举个例子

9159.com 1309159.com 131

flag = "WELcome"
#运行结果
welcome

View Code

.upper()

对字符串里的所有字母转大写

9159.com 1329159.com 133

    def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str

        Return a copy of S converted to uppercase.
        """
        return ""

View Code

举个例子

9159.com 1349159.com 135

flag = "WELcome"
print(flag.upper())
#运行结果
WELCOME

View Code

.title()

对字符串里的单词进行首字母大写转换

9159.com 1369159.com 137

    def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str

        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""

View Code

举个例子

9159.com 1389159.com 139

flag = "welcome frank"
print(flag.title())
#运行结果
Welcome Frank

View Code

.lstrip()

默认去除左边空白字符,可指定去除的字符,去除指定的字符后,会被空白占位。

9159.com 1409159.com 141

  def lstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str

        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

View Code

举个例子

9159.com 1429159.com 143

flag = "     welcome frank"
flag1 = "@@@@welcome frank"
print(flag.lstrip())
print(flag.lstrip("@"))
print(flag.lstrip("@").lstrip())
#运行结果
welcome frank
     welcome frank
welcome frank

View Code

.rstrip()

默认去除右边空白字符,可指定去除的字符,去除指定的字符后,会被空白占位。

9159.com 1449159.com 145

 def rstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.rstrip([chars]) -> str

        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

View Code

举个例子

9159.com 1469159.com 147

flag = "welcome frank    "
flag1 = "welcome frank@@@@"
# print(flag.title())
print(flag.rstrip())
print(flag.rstrip("@"))
print(flag.rstrip("@").rstrip())
#运行结果
welcome frank
welcome frank    #右边有4个空格
welcome frank

View Code

.strip()

默认去除两边空白字符,可指定去除的字符,去除指定的字符后,会被空白占位。

9159.com 1489159.com 149

    def strip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str

        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

View Code

举个例子

9159.com 1509159.com 151

flag = "    welcome frank    "
flag1 = "@@@@welcome frank@@@@"
# print(flag.title())
print(flag.strip())
print(flag.strip("@"))
print(flag.strip("@").strip())
#运行结果
welcome frank
    welcome frank    #右边有4个空格
welcome frank

View Code

.maketrans()和translate()

创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。两个字符串的长度必须相同,为一一对应的关系。

9159.com 1529159.com 153

   def maketrans(self, *args, **kwargs): # real signature unknown
        """
        Return a translation table usable for str.translate().

        If there is only one argument, it must be a dictionary mapping Unicode
        ordinals (integers) or characters to Unicode ordinals, strings or None.
        Character keys will be then converted to ordinals.
        If there are two arguments, they must be strings of equal length, and
        in the resulting dictionary, each character in x will be mapped to the
        character at the same position in y. If there is a third argument, it
        must be a string, whose characters will be mapped to None in the result.
        """
        pass

View Code

9159.com 1549159.com 155

  def translate(self, table): # real signature unknown; restored from __doc__
        """
        S.translate(table) -> str

        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""

View Code

举个例子

9159.com 1569159.com 157

intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "this is string example....wow!!!"
print (str.translate(trantab))
#运行结果
th3s 3s str3ng 2x1mpl2....w4w!!!

View Code

.partition()

以指定字符分割,返回一个元组

9159.com 1589159.com 159

 def partition(self, sep): # real signature unknown; restored from __doc__
        """
        S.partition(sep) -> (head, sep, tail)

        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass

View Code

举个例子

9159.com 1609159.com 161

flag = "welcome"
print(flag.partition("e"))
#运行结果
('w', 'e', 'lcome')

View Code

.replace()

将指定的字符替换为新的字符,可指定替换的个数

9159.com 1629159.com 163

    def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str

        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

View Code

举个例子

9159.com 1649159.com 165

flag = "welcome frank ,e.."
print(flag.replace("e","z"))
print(flag.replace("e","z",1))
#运行结果
wzlcomz frank ,z..
wzlcome frank ,e..

View Code

.rfind()

返回字符串第一次出现的位置,从右向左差,返回索引值,若没有,则返回-1,可根据索引范围查找

9159.com 1669159.com 167

   def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rfind(sub[, start[, end]]) -> int

        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

View Code

举个例子

9159.com 1689159.com 169

flag = "welcome frank ,e.."
print(flag.rfind("e"))
print(flag.rfind("x"))
print(flag.rfind("e",0,3))
#运行结果
15
-1
1

View Code

.rindex()

 查找字符索引值,从右向左,返回索引值,与rfind类似,查找不到会报错

9159.com 1709159.com 171

 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rindex(sub[, start[, end]]) -> int

        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0

View Code

举个例子

9159.com 1729159.com 173

flag = "welcome frank ,e.."
print(flag.rindex("e"))
print(flag.rindex("e",0,3))
#运行结果
15
1

View Code

.rpartition()

以指定字符从右向左分割,只分割一次,返回元组,若没有指定的字符,则在返回的元组前面加两个空字符串

9159.com 1749159.com 175

    def rpartition(self, sep): # real signature unknown; restored from __doc__
        """
        S.rpartition(sep) -> (head, sep, tail)

        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass

View Code

举个例子

9159.com 1769159.com 177

flag = "welcome frank ,e.."
print(flag.rpartition("e"))
print(flag.rpartition("x"))
#运行结果
('welcome frank ,', 'e', '..')
('', '', 'welcome frank ,e..')

View Code

.split()

分割,可以以指定的字符分割,可指定分割的次数,默认从左向右分割,与partition不同的是,split分割后会删除指定的字符,默认以空格为分割符,返回元组。

9159.com 1789159.com 179

    def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.split(sep=None, maxsplit=-1) -> list of strings

        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []

View Code

举个例子

9159.com 1809159.com 181

flag = "welcome frank, e.."
print(flag.split())
print(flag.split('e'))
print(flag.split('e',1))
#运行结果
['welcome', 'frank,', 'e..']
['w', 'lcom', ' frank, ', '..']
['w', 'lcome frank, e..']

View Code

.rsplit()

与split类似,只是它是从右向左分

9159.com 1829159.com 183

    def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings

        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return []

View Code

举个例子

9159.com 1849159.com 185

flag = "welcome frank, e.."
print(flag.rsplit())
print(flag.rsplit('e'))
print(flag.rsplit('e',1))
#运行结果
['welcome', 'frank,', 'e..']
['w', 'lcom', ' frank, ', '..']
['welcome frank, ', '..']

View Code

.splitlines()

字符串转换为列表

9159.com 1869159.com 187

    def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings

        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

View Code

举个例子

9159.com 1889159.com 189

info = "hello,my name is Frank"
print(info.splitlines())
#运行结果
['hello,my name is Frank']

View Code

.startswith()

判断是否以指定字符串或字符开头,可指定索引范围,返回布尔值

9159.com 1909159.com 191

 def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool

        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

View Code

举个例子

9159.com 1929159.com 193

info = "hello,my name is Frank"
print(info.startswith("he"))
print(info.startswith("e"))
print(info.startswith("m",6,-1))
#运行结果
True
False
True

View Code

.swapcase()

将字符串中的大小写互换

9159.com 1949159.com 195

   def swapcase(self): # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str

        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""

View Code

举个例子

9159.com 1969159.com 197

info = "Hello,My name is Frank"
print(info.swapcase())
#运行结果
hELLO,mY NAME IS fRANK

View Code

.zfill()

指定字符串宽度,不足的右边填“0”

9159.com 1989159.com 199

    def zfill(self, width): # real signature unknown; restored from __doc__
        """
        S.zfill(width) -> str

        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""

View Code

举个例子

9159.com 2009159.com 201

info = "Hello,My name is Frank"
print(info.zfill(50))
#运行结果
0000000000000000000000000000Hello,My name is Frank

View Code

 

简历类(Resume) :继承于系统的克隆接口(ICloneable)

点击源码上的复制按键还可以直接将源代码复制下来。

 2.angular.bootstrap()

四、列表

列表是由一系列按特定顺序排列的元素组成。在python中,用方括号([]),来表示列表,并用逗号来分割其中的元素,我们来看一下简单的列表,其type为"list"

9159.com 2029159.com 203

name = ['Frank','Caroline','Bob','Saber']
print(name)  #直接打印会将中括号、引号和逗号都打印出来
print(name[1]) #添加索引可打印对应的值,从索引值从0开始
print(name[-1]) #打印最后一个元素
print(name[0:2]) #用冒号来切片,取右不取左
print(name[-2:]) #冒号右边不写代表一直打印到最后一个
print(name[:1]) #冒号左边不写代表从第“0”个开始打印

View Code

 常见方法如下:

.index()

 查找对应元素的索引值,返回索引值,可以指定索引范围来查找,查找不到会报错

9159.com 2049159.com 205

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

View Code

 举个例子

9159.com 2069159.com 207

name = ['Frank','Caroline','Bob','Saber']
print(name.index("Frank"))
print(name.index("Bob",1,-1))
#运行结果
0
2

View Code

.count()

 计算某个元素的个数

9159.com 2089159.com 209

  def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

View Code

 举个例子

9159.com 2109159.com 211

name = ['Frank','Caroline','Bob','Saber','Frank']
print(name.count('Frank'))
#运行结果
2

View Code

 .append()

 在列表的最后添加元素

9159.com 2129159.com 213

    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -> None -- append object to end """
        pass

View Code

 举个例子

9159.com 2149159.com 215

name = ['Frank','Caroline','Bob','Saber','Frank']
name.append('Mei')
print(name)
#运行结果
['Frank', 'Caroline', 'Bob', 'Saber', 'Frank', 'Mei']

View Code

.clear()

 清空列表

9159.com 2169159.com 217

 def clear(self): # real signature unknown; restored from __doc__
        """ L.clear() -> None -- remove all items from L """
        pass

View Code

 举个例子

9159.com 2189159.com 219

name = ['Frank','Caroline','Bob','Saber','Frank']
name.clear()
print(name)
#运行结果
[]

View Code

 .copy()

 复制列表

9159.com 2209159.com 221

   def copy(self): # real signature unknown; restored from __doc__
        """ L.copy() -> list -- a shallow copy of L """
        return []

View Code

 举个例子

9159.com 2229159.com 223

name = ['Saber','Frank',1,2,[3,4]]
name_cp = name.copy()
print(name_cp)
name[0]='Tom'
name[3]='7'
name[4][0]='8'
print(name)
print(name_cp)
#运行结果
['Saber', 'Frank', 1, 2, [3, 4]]
['Tom', 'Frank', 1, '7', ['8', 4]]
['Saber', 'Frank', 1, 2, ['8', 4]]

View Code

我们会发现,我们给name[0]、name[3]、和name[4][0]都重新赋值了,为什么我重新赋值的name[4][0]会影响到我复制的列表的呢?

首先我们来看一下这个复制图解:

 9159.com 224

我们在复制的时候,新复制的列表都会指向被复制列表的地址空间,name[4]和name_cp[4]本身也是个列表,它们指向的是同一个列表地址空间。我们来看一下给name列表重新赋值后,地址空间的变化:

 9159.com 225

 重新赋值后,内存给name[3]、name[0]、name[4][0]都重新开辟了一块内存空间,name[0]指向了内存地址38703432,name[3]指向了内存地址1400943960,而name[4]还是指向37092936,但是内存地址37092936指向name[4][0]内存地址发生了变化,指向了1400944350,所以,在列表中的列表我们给它重新赋值的时候,也会改变复制列表的值,因为它们的列表里的列表都是指向同一块地址空间。那么如果我们想完全复制怎么办呢?

 可以调用函数deepcopy().

9159.com 2269159.com 227

import copy
name = ['Saber','Frank',1,2,[3,4]]
name_cp=copy.deepcopy(name)
name[4][0]=5
print(name)
print(name_cp)
#运行结果
['Saber', 'Frank', 1, 2, [5, 4]]
['Saber', 'Frank', 1, 2, [3, 4]]

View Code

 9159.com 228

 这样会给复制后的列表中的列表重新开辟一个地址空间,然后指向列表中列表的元素的地址空间,这样你怎么改变原列表name,name_copy都不会改变。

.extend()

 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。

9159.com 2299159.com 230

 def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        pass

View Code

 举个例子

9159.com 2319159.com 232

name = ['Saber','Frank']
nameto = ['Mei','Jack']
name.extend(nameto)
print(name)
#运行结果
['Saber', 'Frank', 'Mei', 'Jack']

View Code

insert()

插入元素,需要指定索引值来插入

9159.com 2339159.com 234

 def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

View Code

 举个例子

9159.com 2359159.com 236

name = ['Saber','Frank']
name.insert(0,'Jack')
print(name)
#运行结果
['Jack', 'Saber', 'Frank']

View Code

 .pop()

 弹出元素,默认弹出最后一个元素,可以指定索引,弹出对应的元素,当列表弹空或者没有指定的索引值会报错,并返回弹出的值

9159.com 2379159.com 238

 def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

View Code

举个例子

9159.com 2399159.com 240

name = ['Saber','Frank','Caroline','Jack']
name.pop()
print(name)
name = ['Saber','Frank','Caroline','Jack']
name.pop(1)
print(name)
#运行结果
['Saber', 'Frank', 'Caroline']
['Saber', 'Caroline', 'Jack']

View Code

.remove()

移除指定的元素

9159.com 2419159.com 242

def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

View Code

 举个例子

9159.com 2439159.com 244

name = ['Saber','Frank','Caroline','Jack']
name.remove('Frank')
print(name)
#运行结果
['Saber', 'Caroline', 'Jack']

View Code

.reverse()

 列表反转,永久修改

9159.com 2459159.com 246

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

View Code

 举个例子

9159.com 2479159.com 248

name = ['Saber','Frank','Caroline','Jack']
name.reverse()
print(name)
#运行结果
['Jack', 'Caroline', 'Frank', 'Saber']

View Code

.sort()

对列表进行排序,永久修改,如果列表中同时存在不同类型的数据,则不能排序,比如含有整型和字符串,传递reverse=True可以倒着排序。

9159.com 2499159.com 250

 def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass

View Code

举个例子

9159.com 2519159.com 252

name = ['Saber','Frank','Caroline','Jack','1','abc','xyz']
name.sort()
print(name)
name.sort(reverse=True)
print(name)
#运行结果
['1', 'Caroline', 'Frank', 'Jack', 'Saber', 'abc', 'xyz']
['xyz', 'abc', 'Saber', 'Jack', 'Frank', 'Caroline', '1']
number = [1,2,3,42,12,32,43,543]
number.sort()
print(number)
number.sort(reverse=True)
print(number)
#运行结果
[1, 2, 3, 12, 32, 42, 43, 543]
[543, 43, 42, 32, 12, 3, 2, 1]

View Code

 

9159.com 2539159.com 254

 

9159.com 2559159.com 256

五、元组

元组和列表类似,不同的是元组的元素是不能修改的,使用小括号"()"括起来,用逗号","分开,其type为tuple

9159.com 2579159.com 258

number = (1,2,2,2,1)
print(type(number))
print(number[0])
print(number[-1])
print(number[1:])
#运行结果
<class 'tuple'>
1
1
(2, 2, 2, 1)

View Code

常见方法如下:

.count()

计算指定元素的个数

9159.com 2599159.com 260

   def count(self, value): # real signature unknown; restored from __doc__
        """ T.count(value) -> integer -- return number of occurrences of value """
        return 0

View Code

举个例子

9159.com 2619159.com 262

number = (1,2,2,2,1)
print(number.count(2))
#运行结果
3

View Code

.index()

查找指定元素的索引,可以指定索引范围来查找

9159.com 2639159.com 264

 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

View Code

举个例子

9159.com 2659159.com 266

number = (1,2,2,2,1)
print(number.index(2))
print(number.index(2,2,-1))
#运行结果
1
2

View Code

 

namespace Ptototype_Pattern
{
    class ReSume:ICloneable
    {
        private string name;
        private string age;
        private string sex;
        private string birthday;
        private string time;
        private string company;
        public ReSume(string name)
        {
            this.name = name;
        }

        /// <summary>
        /// 设置个人信息
        /// </summary>
        /// <param name="age"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        public void SetPersonInfo(string age, string sex, string birthday)
        {
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
        }

        /// <summary>
        /// 设置工作经历
        /// </summary>
        /// <param name="time"></param>
        /// <param name="company"></param>
        public void SetWorkExperice(string time, string company)
        {
            this.time = time;
            this.company = company;
        }

        public void Display()
        {
            Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            Console.WriteLine("在 {0} 工作于 {1} n",time,company);
        }

        public Object Clone()
        {
            return (Object)this.MemberwiseClone();
        }
    }
}

 

<!DOCTYPE HTML>
<meta charset="utf-8">
<head>
</head>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</body>
<script>
    //   angular.bootstrap(); 手动加载模块,   模仿 ng-app自动加载模块    注意不能出现  ng-app
    //创建模块1
  var module1=angular.module('module1',[]);
    module1.controller('controller1', function ($scope) {
        $scope.name='haha';
    })
    //创建模块2
  var module2=angular.module('module2',[]);
  module2.controller('controller2', function ($scope) {
      $scope.name='hehe';
  })
    // 页面加载完成后再加载模块
    angular.element(document).ready(function () {
        angular.bootstrap(document.getElementById("div1"),["module1"]);    //  div1加载 模块1
        angular.bootstrap(document.getElementById("div2"),["module2"]);
    })
</script>
<div id="div1" ng-controller="controller1">div1: {{name}}</div>   <!--  这里要有控制器 -->
<div id="div2" ng-controller="controller2">div2: {{name}}</div>
</body>
</meta>

六、集合

集合是一系列无序的元素组成,所有你不能使用索引值,在打印的时候,元组是自然排序,天然去重的,其type为set

9159.com 2679159.com 268

number = {1,2,3,4,4,5,6}
number1 = {1,6,2,1,8,9,10}
print(number)
print(number1)
#运行结果
{1, 2, 3, 4, 5, 6}
{1, 2, 6, 8, 9, 10}

View Code

常用方法如下

.remove()

移除指定的元素

9159.com 2699159.com 270

  def remove(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set; it must be a member.

        If the element is not a member, raise a KeyError.
        """
        pass

View Code

举个例子

9159.com 2719159.com 272

number = {1,2,3,4,4,5,6}
print(number)
number.remove(1)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6}
{2, 3, 4, 5, 6}

View Code

.pop()

弹出排序过后的第一个元素

9159.com 2739159.com 274

    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        pass

View Code

 

举个例子

9159.com 2759159.com 276

number = {1,2,3,4,4,5,6}
print(number)
number_pop = number.pop()
print(number_pop)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6}
1
{2, 3, 4, 5, 6}

View Code

.clear()

清空列表返回set()

9159.com 2779159.com 278

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        pass

View Code

举个例子

9159.com 2799159.com 280

number = {1,2,3,4,4,5,6}
print(number)
number.clear()
print(number)
#运行结果
{1, 2, 3, 4, 5, 6}
set()

View Code

.copy()

复制集合

9159.com 2819159.com 282

   def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. """
        pass

View Code

举个例子

9159.com 2839159.com 284

number = {1,2,3,4,4,5,6}
print(number)
number2 = number.copy()
number.pop()
print(number)
print(number2)
#运行结果
{1, 2, 3, 4, 5, 6}
{2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}

View Code

.add()

添加元素

9159.com 2859159.com 286

    def add(self, *args, **kwargs): # real signature unknown
        """
        Add an element to a set.

        This has no effect if the element is already present.
        """
        pass

View Code

举个例子

9159.com 2879159.com 288

number = {1,2,3,4,4,5,6}
print(number)
number.add(7)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6, 7}

View Code

.difference()

求差集,可以用“-”代替

9159.com 2899159.com 290

    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set.

        (i.e. all elements that are in this set but not the others.)
        """
        pass

View Code

举个例子

9159.com 2919159.com 292

number = {1,2,3,4,5,6,8,9}
number1 = {2,3,8,9,11,12,10}
print(number.difference(number1))
print(number1.difference(number))
print(number - number1)
print(number1 - number)
##运行结果
{1, 4, 5, 6}
{10, 11, 12}
{1, 4, 5, 6}
{10, 11, 12}

View Code

.union()

求并集,可用“|”代替

9159.com 2939159.com 294

    def union(self, *args, **kwargs): # real signature unknown
        """
        Return the union of sets as a new set.

        (i.e. all elements that are in either set.)
        """
        pass

View Code

举个例子

9159.com 2959159.com 296

number = {1,2,3,4,5,6,8,9}
number1 = {2,3,8,9,11,12,10}
print(number.union(number1))
print(number | number1)
#运行结果
{1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12}
{1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12}

View Code

difference_update.()

差异更新,没有返回值,直接修改集合

9159.com 2979159.com 298

    def difference_update(self, *args, **kwargs): # real signature unknown
        """ Remove all elements of another set from this set. """
        pass

View Code

举个例子

9159.com 2999159.com 300

number = {1,2,3,4,5,6,8,9,13}
number1 = {2,3,8,9,11,12,10}
number.difference_update(number1)
print(number)
#运行结果
{1, 4, 5, 6, 13}

View Code

.discard()

 移除指定元素,如果集合内没有指定的元素,就什么都不做

9159.com 3019159.com 302

    def discard(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set if it is a member.

        If the element is not a member, do nothing.
        """
        pass

View Code

举个例子

9159.com 3039159.com 304

number = {1,2,3,4,5,6,8,9,13}
number.discard(1)
print(number)
#运行结果
{2, 3, 4, 5, 6, 8, 9, 13}

View Code

.intersection()

交集,可以用"&"代替

9159.com 3059159.com 306

def intersection(self, *args, **kwargs): # real signature unknown
        """
        Return the intersection of two sets as a new set.

        (i.e. all elements that are in both sets.)
        """
        pass

View Code

举个例子

9159.com 3079159.com 308

number = {1,2,3,4,5,6,8,9,13}
number1 = {1,2,3,4,5,13,16,17}
print(number.intersection(number1))
print(number & number1)
#运行结果
{1, 2, 3, 4, 5, 13}
{1, 2, 3, 4, 5, 13}

View Code

.intersection_update()

交集更新,没有返回值,直接修改集合

9159.com 3099159.com 310

 def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another. """
        pass

View Code

举个例子

9159.com 3119159.com 312

number = {1,2,3,4,5,6,8,9,13}
number1 = {1,2,3,4,5,13,16,17}
number.intersection_update(number1)
print(number)
#运行结果
{1, 2, 3, 4, 5, 13}

View Code

isdisjoint()

当两个集合没有交集的时候,返回True,否则返回False

9159.com 3139159.com 314

  def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection. """
        pass

View Code

举个例子

9159.com 3159159.com 316

number = {1,2,3,4,5,6,8,9,13}
number1 = {16,17}
print(number.isdisjoint(number1))
#运行结果
True
number = {1,2,3,4,5,6,8,9,13,16}
number1 = {16,17}
#运行结果
False

View Code

.issubset()

 当有2个集合A和B,A.issubset(B),A是否被B包含,如果是则返回True,否则返回False

9159.com 3179159.com 318

  def issubset(self, *args, **kwargs): # real signature unknown
        """ Report whether another set contains this set. """
        pass

View Code

举个例子

9159.com 3199159.com 320

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17}
print(number1.issubset(number))
#运行结果
True

View Code

.issuperset()

当有2个集合A和B,A.issuperset(B),A是否包含B,如果包含则返回True,否则返回False

9159.com 3219159.com 322

 def issuperset(self, *args, **kwargs): # real signature unknown
        """ Report whether this set contains another set. """
        pass

View Code

举个例子

9159.com 3239159.com 324

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17}
print(number.issuperset(number1))
#运行结果
True

View Code

.symmetric_difference()

取两个集合的差集,即取两个集合中对方都没有的元素

9159.com 3259159.com 326

  def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """
        Return the symmetric difference of two sets as a new set.

        (i.e. all elements that are in exactly one of the sets.)
        """
        pass

View Code

举个例子

9159.com 3279159.com 328

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17,18,19}
print(number.symmetric_difference(number1))
#运行结果
{1, 2, 3, 4, 5, 6, 8, 9, 13, 18, 19}

View Code

.symmetric_difference_update()

取两个集合的差集,即取两个集合中对方都没有的元素,并更新到集合中

9159.com 3299159.com 330

   def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. """
        pass

View Code

举个例子

9159.com 3319159.com 332

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17,18,19}
number.symmetric_difference_update(number1)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6, 8, 9, 13, 18, 19}

View Code

.update()

取两个集合的并集,并更新到集合中

9159.com 3339159.com 334

  def update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. """
        pass

View Code

举个例子

9159.com 3359159.com 336

number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17,18,19}
number.update(number1)
print(number)
#运行结果
{1, 2, 3, 4, 5, 6, 8, 9, 13, 16, 17, 18, 19}

View Code

 

View Code

 

View Code

七、字典

在python里面,字典就是一系列的 键-值,每个值都与一个值是一一对应的,键可以是数字、字符串、列表和字典。实际上,可以将任何python对象用作字典的值。

9159.com 3379159.com 338

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
print(info)
print(info['age'])
#运行结果
{'name': 'Frank', 'age': 23, 'hobbby': 'reading', 'address': 'Shanghai'}
23

View Code

方法如下:

.keys()

取出字典的键

9159.com 3399159.com 340

   def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

View Code

举个例子

9159.com 3419159.com 342

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
print(info.keys())
#运行结果
dict_keys(['name', 'age', 'hobbby', 'address'])

View Code

.values()

取出字典的值

9159.com 3439159.com 344

  def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D's values """
        pass

View Code

举个例子

9159.com 3459159.com 346

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
#运行结果
print(info.values())

View Code

.pop()

 弹出一个键值对,必须指定键

 举个例子

9159.com 3479159.com 348

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
info.pop('name')
print(info)
#运行结果
{'age': 23, 'hobbby': 'reading', 'address': 'Shanghai'}

View Code

 .clear()

 清空字典里的键值对

9159.com 3499159.com 350

 def clear(self): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass

View Code

 举个例子

9159.com 3519159.com 352

info = {
    'name':'Frank',
    'age':23,
    'hobbby':'reading',
    'address':'Shanghai',
}
info.clear()
print(info)
#运行结果
{}

View Code

 .update()

 更新字典,如果有2个字典A和B,A.update(B),A和B相同的键的值会被B更新,而B中没有的键值对会被添加到A中

9159.com 3539159.com 354

  def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass

View Code

 举个例子

9159.com 3559159.com 356

info = {
    'name':'Frank',
    'age':23,
    'hobby':'reading',
    'address':'Shanghai',
}
info_new = {
    'age':24,
    'hobby':'sleeping',
    'QQ':'110110',
}
info.update(info_new)
print(info)
#运行结果
{'name': 'Frank', 'age': 24, 'hobby': 'sleeping', 'address': 'Shanghai', 'QQ': '110110'}

View Code

 .copy()

 复制字典

9159.com 3579159.com 358

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
info_new = info.copy()
info['name']='Jack'
info['hobby'][0]='writing'
print(info)
print(info_new)
#运行结果
{'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai'}
{'name': 'Frank', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai'}

View Code

 我们会发现和列表中的copy一样,也存在字典里面的列表的元素被修改后,复制的字典也会自动修改,这个原因其实和前面的是一样的,我们这里也可以使用deep.copy

9159.com 3599159.com 360

import copy
info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
info_new = copy.deepcopy(info)
info['name']='Jack'
info['hobby'][0]='writing'
print(info)
print(info_new)
#运行结果
{'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai'}
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'Shanghai'}

View Code

 那字典里的字典会不会出现相同的问题呢?

9159.com 3619159.com 362

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
    'language':{1:'Python',2:'Go'},
}
info_new = info.copy()
info['name']='Jack'
info['hobby'][0]='writing'
info['language'][2]='Java'
print(info)
print(info_new)
#运行结果
{'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Java'}}
{'name': 'Frank', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Java'}}

View Code

 答案是,是的,当我们想在修改原字典的时候,复制的字典保持不变,还是可以使用deep.copy来解决这个问题。

9159.com 3639159.com 364

import copy
info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
    'language':{1:'Python',2:'Go'},
}
info_new = copy.deepcopy(info)
info['name']='Jack'
info['hobby'][0]='writing'
info['language'][2]='Java'
print(info)
print(info_new)
#运行结果
{'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Java'}}
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Go'}}

View Code

 这也是我们常说的深浅copy!

.fromkeys()

 用来创建一个新的字典

9159.com 3659159.com 366

   def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass

View Code

 举个例子

9159.com 3679159.com 368

key = (1,2,3,4,5)
value = 'Python'
print(dict.fromkeys(key,value))
#运行结果
{1: 'Python', 2: 'Python', 3: 'Python', 4: 'Python', 5: 'Python'}

View Code

 .get()

 根据键返回值,没有键则返回None

9159.com 3699159.com 370

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
print(info.get('hobby'))
#运行结果
['reading', 'sleep']

View Code

 .items()

 返回dict_items(),一般结合for循环使用

9159.com 3719159.com 372

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
print(info.items())
#运行结果
dict_items([('name', 'Frank'), ('age', 23), ('hobby', ['reading', 'sleep']), ('address', 'Shanghai')])

View Code

9159.com 3739159.com 374

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
for k,v in info.items():
    print(k,"---",v)
#运行结果
name --- Frank
age --- 23
hobby --- ['reading', 'sleep']
address --- Shanghai

View Code

.popitem()

 弹出最后一个键值,会返回一个元组,当弹空字典会报错

9159.com 3759159.com 376

 def popitem(self): # real signature unknown; restored from __doc__
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

View Code

 举个例子

9159.com 3779159.com 378

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
    'address':'Shanghai',
}
print(info.popitem())
info.popitem()
print(info)
#举个例子
('address', 'Shanghai')
{'name': 'Frank', 'age': 23}

View Code

.setdefault(key,value)

如果键在字典中,则返回这个键的值,如果不在字典中,则向字典中插入这个键,并返回value,默认value位None
举个例子

9159.com 3799159.com 380

info = {
    'name':'Frank',
    'age':23,
    'hobby':['reading','sleep'],
}
print(info.setdefault('name'))   #存在键name,返回值
print(info)
print(info.setdefault('address','shanghai'))  #不存在键address,返回'shanghai',添加键值对
print(info)
print(info.setdefault('QQ'))    #不存在键QQ,添加键QQ,返回None
print(info)
#运行结果
Frank
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep']}
shanghai
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'shanghai'}
None
{'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'shanghai', 'QQ': None}

View Code

 

今天就写到这里了,欢迎各位大佬指出错误和不足之处,谢谢了!

 

客户端类(TestMain)

 

 3.angular.element()  应该用 directive

9159.com 3819159.com 382

 

9159.com 3839159.com 384

namespace Ptototype_Pattern
{
    class TestMain
    {
        static void Main(string[] args)
        {
            ReSume A = new ReSume("张三");
            A.SetPersonInfo("25","男","1988-10-10");
            A.SetWorkExperice("2010--2013", "X公司");

            ReSume B = (ReSume)A.Clone();
            B.SetWorkExperice("2009--2010", "Y公司");

            ReSume C = (ReSume)A.Clone();
            C.SetWorkExperice("2006--2009", "Z公司");

            A.Display();
            B.Display();
            C.Display();

            Console.ReadLine();

        }
    }
}

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <style>
        .a{color:red;}
    </style>
</head>
<body>
    <p>12345</p>
    <script>
        var p1=document.getElementsByTagName("p")[0];
        angular.element(p1).addClass('a');
    </script>
</body>
</html>

View Code

 

View Code

9159.com 385

 

 4. JSON.stringify()  // 对象转成string

 

 

9159.com 3869159.com 387

深复制和浅复制:MemberwiseClone 方法创建一个浅表副本,方法是创建一个新对象,然后将当前对象的非静态字段复制到该新对象。 如果字段是值类型的,则对该字段执行逐位复制。 如果字段是引用类型,则复制引用但不复制引用的对象;因此,原始对象及其复本引用同一对象。

 

  <script>
        var a={a:1,b:2};
        console.log("xx: "+typeof a+" :"+a);
        var b=JSON.stringify(a);    // 转成string 类型
        console.log("x2x: "+typeof b+" :"+b);
    </script>

引用类型的例子如下:

View Code

新添加工作经历类(WorkExperice)

 5.angular.extend(obj2,obj1)  //  把obj1的属性复制给obj2并把结果赋值给obj2  

 

9159.com 3889159.com 389

9159.com 3909159.com 391

<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script>
        var obj1={name:'tom'};
        var obj2={sex:'female'};
        var obj_new=angular.extend(obj2,obj1);    // 返回值赋给obj2
        console.log("obj1: "+JSON.stringify(obj1));
        console.log("obj2: "+JSON.stringify(obj2));
        console.log("obj_new: "+JSON.stringify(obj_new));
    </script>
namespace Ptototype_Pattern
{
    class WorkExperice
    {
        private string workTime;
        private string workCompany;
        /// <summary>
        /// 工作时间
        /// </summary>
        public string WorkTime
        {
            get { return workTime; }
            set { workTime = value; }
        }

        /// <summary>
        /// 工作企业
        /// </summary>
        public string WorkCompany
        {
            get { return workCompany; }
            set { workCompany = value; }
        }
    }
}

View Code

View Code

 6. webStorm 智能提示jq angularjs语法

 

9159.com 392

简历类(Resume) :继承于系统的克隆接口(ICloneable)

 7.声明 controllers 的推荐的方法是使用数组表示法

9159.com 3939159.com 394

9159.com 395

namespace Ptototype_Pattern
{
    class ReSume:ICloneable
    {
        private string name;
        private string age;
        private string sex;
        private string birthday;
        //private string time;
        //private string company;
        private WorkExperice work;
        public ReSume(string name)
        {
            this.name = name;
            work = new WorkExperice();

        }

        /// <summary>
        /// 设置个人信息
        /// </summary>
        /// <param name="age"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        public void SetPersonInfo(string age, string sex, string birthday)
        {
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
        }

        /// <summary>
        /// 设置工作经历
        /// </summary>
        /// <param name="time"></param>
        /// <param name="company"></param>
        public void SetWorkExperice(string time, string company)
        {
            //this.time = time;
            //this.company = company;
            work.WorkTime = time;
            work.WorkCompany = company;

        }

        public void Display()
        {
            //Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            //Console.WriteLine("在 {0} 工作于 {1} n",time,company);

            Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            Console.WriteLine("在 {0} 工作于 {1} n", work.WorkTime, work.WorkCompany);

        }

        public Object Clone()
        {
            return (Object)this.MemberwiseClone();
        }
    }
}

8.angularjs.forEach()  angularjs.fromJson()

View Code

9159.com 3969159.com 397

客户端不变:(全为Z公司)

<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script>
        /* 1. angularjs.forEach();  */
        var objs =[{a:1},{a:2}];
        angular.forEach(objs, function(data,index,array){
            //data等价于array[index]
            console.log(data.a+'='+array[index].a);
            console.log("xx: "+data.a);
        });
        /*  2.  angular.fromJson()  */
        var json='{"name":"haha","password":"321"}';
        var jsonStr=angular.fromJson(json);     //  把json转成对象
        console.log("jsonStr: "+typeof jsonStr);
        console.log("jsonStr name: "+jsonStr.name);
    </script>

9159.com 398

View Code

MemberwiseClone 方法创建一个浅表副本,对于引用类型复制引用,但不复制引用的对象

 9. ng-class

改为深复制如下:

9159.com 3999159.com 400

工作经历类(WorkExperice)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .testCol{color:blue;}
        .testSize{font-size: 30px;}
        .testBorder{border: 1px solid red;}
        .red{color:red;}
    </style>
</head>

<body>
    <div ng-app="app" ng-controller="myCtrl">

    <p ng-class="{testCol:color,testSize:size,testBorder:border}">{{name}}</p>
                    <!--  属性是样式,值是true or false -->
        <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
        <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
        <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
        <input type="checkbox" ng-model="error"> error (apply "red" class)
        <hr>


        </div>
        <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
        <script>
            angular.module("app",[])
                .controller("myCtrl",["$scope", function ($scope) {
                     $scope.name='haha';
                        $scope.color=true;     /*  true 则应用该样式*/
                        $scope.size=false;
                        $scope.border=true;
                }])
        </script>
</body>
</html>

 

View Code

9159.com 4019159.com 402

 10.ng-copy 复制  ng-paste粘贴  ng-cut 剪切

namespace Ptototype_Pattern
{
    class WorkExperice:ICloneable
    {
        private string workTime;
        private string workCompany;
        /// <summary>
        /// 工作时间
        /// </summary>
        public string WorkTime
        {
            get { return workTime; }
            set { workTime = value; }
        }

        /// <summary>
        /// 工作企业
        /// </summary>
        public string WorkCompany
        {
            get { return workCompany; }
            set { workCompany = value; }
        }

        public Object Clone()
        {
            return (object)this.MemberwiseClone();
        }
    }
}

9159.com 4039159.com 404

View Code

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>

</head>
<body>
<div ng-app="app" ng-controller="myCtrl">
        <div ng-bind="name"></div>
    <input type="text" ng-model="name" ng-copy="copy()"/>
    </div>
    <script>
        /*触发条件:复制。鼠标右键复制和快捷键Ctrl+C都会触发。*/  
        angular.module("app",[])
            .controller("myCtrl",["$scope", function ($scope) {
                 $scope.name='haha';
                    $scope.copy= function () {
                        alert(1);
                    }
            }])

    </script>
</body>
</html>

 

View Code

简历类(Resume) :继承于系统的克隆接口(ICloneable)

 11.ng-list

9159.com 4059159.com 406

9159.com 4079159.com 408

namespace Ptototype_Pattern
{
    class ReSume:ICloneable
    {
        private string name;
        private string age;
        private string sex;
        private string birthday;
        //private string time;
        //private string company;
        private WorkExperice work;
        public ReSume(string name)
        {
            this.name = name;
            work = new WorkExperice();

        }
        public ReSume(WorkExperice work)
        {
            this.work = (WorkExperice)work.Clone();
        }

        /// <summary>
        /// 设置个人信息
        /// </summary>
        /// <param name="age"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        public void SetPersonInfo(string age, string sex, string birthday)
        {
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
        }

        /// <summary>
        /// 设置工作经历
        /// </summary>
        /// <param name="time"></param>
        /// <param name="company"></param>
        public void SetWorkExperice(string time, string company)
        {
            //this.time = time;
            //this.company = company;
            work.WorkTime = time;
            work.WorkCompany = company;

        }

        public void Display()
        {
            //Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            //Console.WriteLine("在 {0} 工作于 {1} n",time,company);

            Console.WriteLine("姓名:{0}  年龄:{1} 出生日期:{2}", name, age, birthday);
            Console.WriteLine("在 {0} 工作于 {1} n", work.WorkTime, work.WorkCompany);

        }

        public Object Clone()
        {
            //return (Object)this.MemberwiseClone();
            ReSume resum = new ReSume(this.work);
            resum.name = this.name;
            resum.age = this.age;
            resum.birthday = this.birthday;
            return resum;
        }
    }
}
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="myCtrl">
    <p>ng-list自定义输入数组   a.b.c.d </p>
    <input type="text" ng-model="lists" ng-list="."/><br/>
    {{lists}}
    <li ng-repeat="list in lists">{{list}}</li>
    </div>
    <script>
        angular.module("app",[])
            .controller("myCtrl",["$scope", function ($scope) {
                $scope.lists=['a','b','c'];
            }])
    </script>
</body>
</html>

View Code

View Code

客户端不变:

 12. angular 获得input的值

9159.com 409

9159.com 4109159.com 411

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
  <!--<script src="http://apps.bdimg.com/libs/angular.js/1.5.3/angular.min.js"></script>-->
  <script src="//cdn.bootcss.com/angular.js/1.5.3/angular.min.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="myCtrl">
<input type="text" ng-model="orderNum"/>
  <button ng-click="check()">btn</button>
</div>
<script>
  angular.module("app",[])
    .controller("myCtrl", function ($scope) {
      $scope.check= function () {
         alert($scope.orderNum)
      }
    })
</script>
</body>
</html>

 

View Code

 

 13.angular factory service

 

9159.com 4129159.com 413

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
  <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="appTest" ng-controller="MyController">
<ul>
  <li ng-repeat="test in tests">
    id: {{test.id}} 名字: {{test.name}}
    信息: {{test.lastText}}
    <button ng-click="remove(test)">delete</button>
  </li>
</ul>
</div>
<script>
  var appTest = angular.module("appTest",[]);
  appTest.factory("myFactory", function () {
      var f={};
      f.remove= function (arr,item) {
        return arr.splice(arr.indexOf(item),1);
      }
      return f;
    });
  appTest.service("myService", function (myFactory) {
      this.remove=function(arr,item){
        return myFactory.remove(arr,item);
      }
    });
  appTest.controller("MyController", function ($scope,$http,myService) {
      $http.get("test.json").success(function (data) {
        $scope.tests=data;
      });
      //    把factory service 删除,直接在控制器中可以实现删除效果
      /* $scope.remove= function (test) {
       $scope.tests.splice($scope.tests.indexOf(test),1);
       }*/
      $scope.remove= function (test) {
         myService.remove($scope.tests,test);
      }
    });
</script>

</body>
</html>

 

View Code

14.angular 指令(1)

9159.com 4149159.com 415

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body ng-app="app">
  <hello-word>12345</hello-word>
  <hello-word></hello-word>
  <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
  <script>
    angular.module("app",[])
      .directive('helloWord', function () {
        return{
          restrict:'E',    //  E 元素  A 属性
          template:'<div>hi, how are yousss<br/></div>',
          replace:true,    /* 隐藏 <hello-word>标签 */
          transclude:true     /* 保留 标签里面的内容: 12345 */
        }
      })
  </script>
</body>
</html>

View Code

15.anguar 指令 link

9159.com 4169159.com 417

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
  <style>
    .expander {
      border: 1px solid black;
      width: 250px;
    }

    .expander>.title {
      background-color: black;
      color: white;
      padding: .1em .3em;
      cursor: pointer;
    }

    .expander>.body {
      padding: .1em .3em;
    }
  </style>
</head>
<body ng-app="expanderModule">
<div ng-controller='SomeController'>
  <expander class='expander' expander-title='title'>
    {{text}}
  </expander>

</div>
  <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
  <script>
    var expanderModule=angular.module('expanderModule', [])
    expanderModule.directive('expander', function() {
      return {
        restrict : 'EA',
        replace : true,
        transclude : true,
        scope : {
          title : '=expanderTitle'
        },
        template : '<div>'
        + '<div class="title" ng-click="toggle()">{{title}}</div>'
        + '<div class="body" ng-show="showMe" ng-transclude></div>'
        + '</div>',
        link : function(scope, element, attrs) {
          scope.showMe = false;
          scope.toggle = function toggle() {
            scope.showMe = !scope.showMe;
          }
        }
      }
    });
    expanderModule.controller('SomeController',function($scope) {
      $scope.title = '点击展开';
      $scope.text = '这里是内部的内容。';
    });
  </script>
</body>
</html>

View Code

 

本文由9159.com发布于编程,转载请注明出处:超出范围的为长整型,点击源码上的复制按键还

关键词: