Chapter 1 基本的对象类型

I skipped many sections and only revisit the parts I usually forgot in the daily coding experience.

1.5

1.5.9 常用的字符串方法


In [14]:
for i in dir(str):
    print(i,end = ', ')


__add__, __class__, __contains__, __delattr__, __dir__, __doc__, __eq__, __format__, __ge__, __getattribute__, __getitem__, __getnewargs__, __gt__, __hash__, __init__, __init_subclass__, __iter__, __le__, __len__, __lt__, __mod__, __mul__, __ne__, __new__, __reduce__, __reduce_ex__, __repr__, __rmod__, __rmul__, __setattr__, __sizeof__, __str__, __subclasshook__, capitalize, casefold, center, count, encode, endswith, expandtabs, find, format, format_map, index, isalnum, isalpha, isascii, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable, isspace, istitle, isupper, join, ljust, lower, lstrip, maketrans, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill, 

In [16]:
help(str.join)


Help on method_descriptor:

join(self, iterable, /)
    Concatenate any number of strings.
    
    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.
    
    Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'


In [17]:
note = "I skipped many sections and only revisit the parts I usually forgot in the daily coding experience."
print(type(note))


<class 'str'>

In [20]:
note.isalpha()
# check whether the chracters in the string are all alphabetic. If there is one not letter, return False
# spacing is not the the letter, hence it returns false here


Out[20]:
False

In [34]:
note_list = note.split()
print(note_list)
note_no_spacing = ''.join(note_list)
note_no_spacing = note_no_spacing[:-1] # remove period in the end
print(note_no_spacing)
print(type(note_no_spacing))
print(note_no_spacing.isalpha())


['I', 'skipped', 'many', 'sections', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'usually', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.']
IskippedmanysectionsandonlyrevisitthepartsIusuallyforgotinthedailycodingexperience
<class 'str'>
True

In [35]:
note.istitle()


Out[35]:
False

In [38]:
note_being_title = note.title()
print(note_being_title)
print(note)


I Skipped Many Sections And Only Revisit The Parts I Usually Forgot In The Daily Coding Experience.
I skipped many sections and only revisit the parts I usually forgot in the daily coding experience.

In [39]:
note.isupper()


Out[39]:
False

In [41]:
note.upper()


Out[41]:
'I SKIPPED MANY SECTIONS AND ONLY REVISIT THE PARTS I USUALLY FORGOT IN THE DAILY CODING EXPERIENCE.'

In [42]:
note.capitalize()


Out[42]:
'I skipped many sections and only revisit the parts i usually forgot in the daily coding experience.'

In [43]:
if 'skip' in note:
    print(True)


True

In [49]:
note_with_spacing_start_end = '     '  + note + ' '
print(note_with_spacing_start_end)
print(len(note_with_spacing_start_end))
note_remove_spacing = note_with_spacing_start_end.strip()
print(len(note_remove_spacing))
print(len(note))


     I skipped many sections and only revisit the parts I usually forgot in the daily coding experience. 
105
99
99

1.8 比较列表和字符串


In [50]:
note


Out[50]:
'I skipped many sections and only revisit the parts I usually forgot in the daily coding experience.'

In [52]:
lst = note.split()
print(lst)


['I', 'skipped', 'many', 'sections', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'usually', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.']

In [53]:
id(lst)


Out[53]:
4529871496

In [55]:
lst1 = lst.remove
print(id(lst1))


4528297160

In [58]:
lst.append('hello')

In [60]:
print(lst)


['I', 'skipped', 'many', 'sections', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'usually', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.', 'hello']

In [61]:
id(lst) # list is changed in-place by "append", hence the id in memory is same.


Out[61]:
4529871496

In [63]:
lst2 = ["we", "are", "finghting", "against", "COVID2019"]
print(lst2)
print(id(lst2))


['we', 'are', 'finghting', 'against', 'COVID2019']
4529904904

In [64]:
lst.extend(lst2)
print(lst)
print(id(lst))


['I', 'skipped', 'many', 'sections', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'usually', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.', 'hello', 'we', 'are', 'finghting', 'against', 'COVID2019']
4529871496

In [65]:
del lst[2]
print(lst)


['I', 'skipped', 'sections', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'usually', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.', 'hello', 'we', 'are', 'finghting', 'against', 'COVID2019']

In [66]:
lst[2] = 'lots of'
print(lst)


['I', 'skipped', 'lots of', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'usually', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.', 'hello', 'we', 'are', 'finghting', 'against', 'COVID2019']

In [75]:
lst.insert(3,'sections')
print(lst)


['I', 'skipped', 'lots of', 'sections', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'usually', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.', 'hello', 'we', 'are', 'finghting', 'against', 'COVID2019']

In [79]:
lst.remove('usually')
print(lst)


['I', 'skipped', 'lots of', 'sections', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.', 'hello', 'we', 'are', 'finghting', 'against', 'COVID2019']

In [81]:
lst.pop(0)


Out[81]:
'I'

In [83]:
print(lst)


['skipped', 'lots of', 'sections', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.', 'hello', 'we', 'are', 'finghting', 'against', 'COVID2019']

In [84]:
lst[0] = "I"
print(lst)


['I', 'lots of', 'sections', 'and', 'only', 'revisit', 'the', 'parts', 'I', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.', 'hello', 'we', 'are', 'finghting', 'against', 'COVID2019']

In [86]:
lst.pop(3)


Out[86]:
'and'

In [87]:
print(lst)


['I', 'lots of', 'sections', 'only', 'revisit', 'the', 'parts', 'I', 'forgot', 'in', 'the', 'daily', 'coding', 'experience.', 'hello', 'we', 'are', 'finghting', 'against', 'COVID2019']

In [89]:
lst.pop(3,4) # note that pop only accpets one argument


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-5f797f355a51> in <module>
----> 1 lst.pop(3,4)

TypeError: pop() takes at most 1 argument (2 given)

In [109]:
from __future__ import division
import numpy as np

a = np.random.randn(3)
print(type(a))
print(id(a))
a_list = a.tolist()
print(id(a_list))


<class 'numpy.ndarray'>
4577429744
4576698248

In [110]:
a_list


Out[110]:
[-0.40132837850574876, 1.704739872321806, 2.4441571386539986]

In [115]:
a_list.sort()

In [121]:
a_list


Out[121]:
[-0.40132837850574876, 1.704739872321806, 2.4441571386539986]

In [122]:
a_list.reverse()
a_list


Out[122]:
[2.4441571386539986, 1.704739872321806, -0.40132837850574876]

In [120]:
a = [3,5,1,6]
a.reverse()
a


Out[120]:
[6, 1, 5, 3]

In [127]:
reversed(a)
a


Out[127]:
[6, 1, 5, 3]

In [128]:
a.reverse()

In [129]:
a


Out[129]:
[3, 5, 1, 6]

In [137]:
b = [i for i in reversed(a)]
b


Out[137]:
[6, 1, 5, 3]

In [134]:
help(reversed)


Help on class reversed in module builtins:

class reversed(object)
 |  reversed(sequence, /)
 |  
 |  Return a reverse iterator over the values of the given sequence.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __length_hint__(...)
 |      Private method returning an estimate of len(list(it)).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  __setstate__(...)
 |      Set state information for unpickling.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.

1.8.4 列表和字符串的相互转化


In [142]:
setence_1 = "I am a chef here, but not the bos! Bos is standing\nthere!"

In [143]:
setence_1.split()


Out[143]:
['I',
 'am',
 'a',
 'chef',
 'here,',
 'but',
 'not',
 'the',
 'bos!',
 'Bos',
 'is',
 'standing',
 'there!']

In [145]:
help(str.split)


Help on method_descriptor:

split(self, /, sep=None, maxsplit=-1)
    Return a list of the words in the string, using sep as the delimiter string.
    
    sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.


In [148]:
setence_1.split(' ', 0)


Out[148]:
['I am a chef here, but not the bos! Bos is standing\nthere!']

In [149]:
setence_1.split(' ', 1)


Out[149]:
['I', 'am a chef here, but not the bos! Bos is standing\nthere!']

In [150]:
setence_1.split(' ', 2)


Out[150]:
['I', 'am', 'a chef here, but not the bos! Bos is standing\nthere!']

In [151]:
setence_1.split(' ', -1)


Out[151]:
['I',
 'am',
 'a',
 'chef',
 'here,',
 'but',
 'not',
 'the',
 'bos!',
 'Bos',
 'is',
 'standing\nthere!']

In [ ]:


In [152]:
s = 'He is, a farmer.'

In [161]:
ass


Out[161]:
['He is', ' a farmer.']

In [163]:
ass = s.split(',')
print(ass)
xx = []
for i in ass:
    xx.extend(i.split())
print(xx)
new_str = ' '.join(xx)
print(new_str)


['He is', ' a farmer.']
['He', 'is', 'a', 'farmer.']
He is a farmer.

1.10.1 创建字典

方法1: 直接增加键值对方式


In [5]:
fang={} # an empty dict
print(id(fang))
fang['name'] = "Pipi"
print(fang)
print(fang.keys())
print(id(fang))


4382811984
{'name': 'Pipi'}
dict_keys(['name'])
4382811984

我们可以看出保存在内存中的字典可以被原地修改,这点类似于list


In [ ]:
方法2:利用元祖构建字典

In [6]:
name_list = (["family-name", "fang"], ["given-name", "Pipi"])
print(name_list)
name_dic = dict(name_list)
print(name_dic)


(['family-name', 'fang'], ['given-name', 'Pipi'])
{'family-name': 'fang', 'given-name': 'Pipi'}

Alternatively, we can use:


In [7]:
name_dict = dict(family_name="FANG", given_name="Pupu")
print(name_dict)


{'family_name': 'FANG', 'given_name': 'Pupu'}

In [ ]:
方法3利用fromkeys

In [8]:
web = {}.fromkeys(("family-name", "given-name"), "FANG")
print(web)


{'family-name': 'FANG', 'given-name': 'FANG'}

In [12]:
web1 = {}.fromkeys(("family-name", "given-name"), ("FANG", "Pipi"))
print(web1)


{'family-name': ('FANG', 'Pipi'), 'given-name': ('FANG', 'Pipi')}

1.10.2 访问字典的值


In [13]:
person_info = {}.fromkeys(("lucky-numer1", "lucky-number2"), 99)
print(person_info)


{'lucky-numer1': 99, 'lucky-number2': 99}

In [14]:
person_info['lucky-number2']


Out[14]:
99

python调取列表时候总是需要从头开始读取,直到找到指定的那个索引值。但是,在字典中是通过“键”来得到值的,因此效率更高。


In [ ]: