1.
different of assignment variable and list
for variable: just copy the content of the other
like below:
for list: copy the address of the other
like below:
2. contrast from string\list\pair
the difference like the code below:
3. the defence style function
prevent unreasonable input and suggest reasonable solution. like below function the argument must be string,if not return warn.
4. dictionary in python like hash pair in other programming language
the character reflected in below code:
for variable: just copy the content of the other
like below:
点击(此处)折叠或打开
- >>> var1 = 'hello'
- >>> var2 = var1
- >>> var1 = 'world'
- >>> var1
- 'world'
- >>> var2
- 'hello'
like below:
点击(此处)折叠或打开
- >>> list1 = []
- >>> nested = [list1, list1, list1]
- >>> nested
- [[], [], []]
- >>> nested[1].append('Hello ')
- >>> nested
- [['Hello '], ['Hello '], ['Hello ']]
- >>> list1.append('world!!')
- >>> nested
- [['Hello ', 'world!!'], ['Hello ', 'world!!'], ['Hello ', 'world!!']]
the difference like the code below:
点击(此处)折叠或打开
- strings = 'I am a good student!!'
- >>> lines = ['zhang', 'pei', 'hua', 'hello', 'world']
- >>> pairs = (6, 'dog', 'cat')
- >>> strings[2], lines[2], pairs[2]
- ('a', 'hua', 'cat')
- >>> len(strings), len(lines), len(pairs)
- (21, 5, 3)
prevent unreasonable input and suggest reasonable solution. like below function the argument must be string,if not return warn.
点击(此处)折叠或打开
- >>> def tag(word):
- ... assert isinstance(word, basestring), "argument \
- ... to tag() must be a string"
- ... if word in ['a', 'the', 'all']:
- ... return 'det'
- ... else:
- ... return 'noun'
- ...
- >>> tag('hello')
- 'noun'
- >>> tag(['hello'])
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- File "<stdin>", line 3, in tag
- AssertionError: argument to tag() must be a string
the character reflected in below code:
点击(此处)折叠或打开
- >>> pos = {'colorless':'ADJ', 'ideas':'N', 'sleep':'V'}
- >>> pos
- {'sleep': 'V', 'ideas': 'N', 'colorless': 'ADJ'}
- >>> pos2 = dict(colorless='ADJ', ideas='N', sleep='V')
- >>> pos2
- {'sleep': 'V', 'ideas': 'N', 'colorless': 'ADJ'}
- >>> pos['sleep']
- 'V'
- >>> pos['sleep'] = ['N','V']
- >>> pos
- {'sleep': ['N', 'V'], 'ideas': 'N', 'colorless': 'ADJ'}