1.different of assignment variable and list
for variable: just copy the content of the other
like below:
-
>>> var1 = 'hello'
-
>>> var2 = var1
-
>>> var1 = 'world'
-
>>> var1
-
'world'
-
>>> var2
-
'hello'
for list: copy the address of the other
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!!']]
2. contrast from string\list\pair
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)
3. the defence style function
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
4. dictionary in python like hash pair in other programming language
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'}
阅读(1136) | 评论(0) | 转发(0) |