0
0

Some tips about python this week

Robin Dong 发表于 2018年11月29日 14:26 | Hits: 432
Tag: develope | python

List of lists in python
Created a list of lists by using multiply symbol:

>>> a = [[]] * 2
>>> a
[[], []]
>>> a[0].append('hello')
>>> a
[['hello'], ['hello']]

It’s weird that adding one item to first list have side-effect on second list! Seems ‘* 2’ makes two reference for one list.
How to avoid this then? The answer is using normal syntax:

>>> a = [[], []]
>>> a
[[], []]
>>> a[0].append('hello')
>>> a
[['hello'], []]
>>>

A difference between python2 and python3
There are many trivial differences between python3 and python3, and I luckily found one this week:

# In python2
>>> dict = {1: 'hello', 2: 'world'}
>>> dict.values()
['hello', 'world']

# In python3
>>> dict = {1: 'hello', 2: 'world'}
>>> dict.values()
dict_values(['hello', 'world'])

In python3, the values() of a dictionary is not type of ‘list’ but ‘dict_values’. To be compatible to python2, we need to add

list(dict.values())

for old python2 codes.

原文链接: http://donghao.org/2018/11/29/some-tips-about-python-this-week/

0     0

评价列表(0)