Python学习笔记-Day09

Python学习笔记

Day_09-曾经的对象

Vamei:从最初的“Hello World!”,一路狂奔到对象面前,俗话说,人生就像是一场旅行,重要的是沿途的风景。事实上,前面几张已经多次出现对象,只不过,那时候没有引入对象的概念,现在让我们回头看看曾经错过的对象。

9.1 列表对象

首先,让我们定义一个列表a,使用type()获取列表的类型。

>>> a = [1, 2, 5, 2, 5]
>>> type(a)

输出结果如下:

<class 'list'>

从返回结果可以看出,a属于list类型,也就是列表类型。而list是Python的内置类,我们可以通过dir()和help()来进一步查看内置类list的相关说明。由于说明文件100多行,我进行了节减显示。

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list(iterable=(), /)
 |  
 |  Built-in mutable sequence.
 |  
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key]
 | 
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __len__(self, /)
 |      Return len(self).

 |  __reversed__(self, /)
 |      Return a reverse iterator over the list.
 |  
 |  append(self, object, /)
 |      Append object to the end of the list.
 |  
 |  clear(self, /)
 |      Remove all items from list.
 |  
 |  copy(self, /)
 |      Return a shallow copy of the list.
 |  
 |  count(self, value, /)
 |      Return number of occurrences of value.
 |  
 |  extend(self, iterable, /)
 |      Extend list by appending elements from the iterable.
 |  
 |  index(self, value, start=0, stop=9223372036854775807, /)
 |      Return first index of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  insert(self, index, object, /)
 |      Insert object before index.
 |  
 |  pop(self, index=-1, /)
 |      Remove and return item at index (default last).
 |      
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(self, value, /)
 |      Remove first occurrence of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(self, /)
 |      Reverse *IN PLACE*.
 |  
 |  sort(self, /, *, key=None, reverse=False)
 |      Sort the list in ascending order and return None.
 |      
 |      The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
 |      order of two equal elements is maintained).
 |      
 |      If a key function is given, apply it once to each list item and sort them,
 |      ascending or descending, according to their function values.
 |      
 |      The reverse flag can be set to sort in descending order.
 |  
 |  ------------------------------------------------------- |  Data and other attributes defined here:
 |  
 |  __hash__ = None

说明中列举了list类中的属性和方法。尤其是后面所罗列的list的一些方法。前面我学习list的知识的时候其实已经都涉及到了,现在正好从对象的角度来重新认识,也相当于重新复习西下list的相关知识。

>>> a = [1, 3, 4, 8, 10.0, -11, True, False, "Hello"]
>>> a.count(3)
1
>>> a.index(4)
2
>>> a.append(6)
>>> a
[1, 3, 4, 8, 10.0, -11, True, False, 'Hello', 6]
>>> a.sort()
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    a.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
>>> a.reverse()
>>> a
[6, 'Hello', 10.0, 8, 4, 3, True, 1, False, -11]
>>> a.pop()
-11
>>> a.remove(True)
>>> a
[6, 'Hello', 10.0, 8, 4, 3, 1, False]
>>> a.insert(3,4)
>>> a
[6, 'Hello', 10.0, 4, 8, 4, 3, 1, False]
>>> a.clear()
>>> a
[]

9.2 元组和字符串对象

前面的学习中我们知道,元组和字符串都属于不可变的数据类型。

1、元组

参考上面列表的做法,我们定义一个元组。

>>> a = (2, 7, 12)
>>> type(a)    # <class 'tuple'>

通过查看dir()和help(),我们可以看到tuple元组的属性和方法。其中,由于元组的不可变性,其方法仅支持count和index两种。

Help on class tuple in module builtins:

class tuple(object)
 |  tuple(iterable=(), /)
 |  
 |  Built-in immutable sequence.
 |  
 |  If no argument is given, the constructor returns an empty tuple.
 |  If iterable is specified the tuple is initialized from iterable's items.
 |  
 |  If the argument is a tuple, the return value is the same object.
 |  
 |  Built-in subclasses:
 |      asyncgen_hooks
 |      UnraisableHookArgs
 |  
 |  Methods defined here:
 |
 |  count(self, value, /)
 |      Return number of occurrences of value.
 |  
 |  index(self, value, start=0, stop=9223372036854775807, /)
 |      Return first index of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.

因此,以定义好的元组a为例:

>>> a.count(7)
1
>>> a.index(12)
2

2、字符串

字符串虽然也是不可变的一种数据类型,我们定义的字符串也是属于<class 'str'>的一个对象。

但是我们通过查阅help(str)文件会发现,有关字符串的方法确实非常之多。仔细查阅发现,除了计数、查找索引、判断等的一些操作之外,其余关于字符串的操作都是删除原字符串然后再建立一个新的字符串,逻辑上没有违背不可变性。下面列举几个典型的字符串方法。

>>> str = "Hello World"
>>> sub = "World"
>>> str.count(sub)
1
>>> str.find(sub)
6
>>> str.index(sub)
6
>>> str.isalnum()
False
>>> str.isalpha()
False
>>> str.isdigit()
False
>>> str.istitle()
True
>>> str.islower()
False
>>> str.isupper()
False
>>> str.lower()
'hello world'
>>> str.upper()
'HELLO WORLD'
>>> str
'Hello World'

通过例证发现,前面的几个是查询索引和判断的操作,后面两种是将字符串的全部字母变成大写或者小写。通过最后调用str发现,原来的str字符串还是原来的,并未被改变。

9.3 词典对象

词典同样属于一个类,<class 'dict'>

通过help(dict)可以看到,词典定义的方法不多,主要有以下几种:

D.clear()  #清空词典所有元素,返回空词典
D.copy()  #复制一个词典
D.get(key)  #如果键存在,返回值,如果不存在,返回None。
D.items() #返回词典中的元素,dict_item([(key1, value1), (key2, values), ...])
D.keys() #返回词典中所有的key,dict_keys([key1, key2, key3...])
D.pop(key)  #删除对应key及值,返回对应key的值。
D.popitem() #删除词典最后一个key及对应的value,返回这个key及对应value组成的一个元组。
D.setdefault(key, value)  #向词典中增加一组key及value,如果只有key,且这个key在词典中不存在,则在词典中增加key:none
D.update() #
D.values() #返回词典中所有的value,dict_values([value1, value2...])

我们定义一个dict,然后使用一下上面的方法。

>>> dict1 = {"a":12, "b":20, "c":33 }
>>> dict1.clear()
>>> dict1
{}
>>> dict1 = {"a":12, "b":20, "c":33 }
>>> dict1.copy()
{'a': 12, 'b': 20, 'c': 33}
>>> dict1.get("a")
12
>>> dict1.get("d")
>>> dict1.items()
dict_items([('a', 12), ('b', 20), ('c', 33)])
>>> dict1.keys()
dict_keys(['a', 'b', 'c'])
>>> dict1.values()
dict_values([12, 20, 33])
>>> dict1.pop("b")
20
>>> dict1
{'a': 12, 'c': 33}
>>> dict1.popitem()
('c', 33)
>>> dict1 = {"a":12, "b":20, "c":33 }
>>> dict1.setdefault("d")
>>> dict1
{'a': 12, 'b': 20, 'c': 33, 'd': None}
>>> dict1.setdefault("d", 44)
>>> 
>>> dict1
{'a': 12, 'b': 20, 'c': 33, 'd': None}
>>> dict1.setdefault("f", 55)
55
>>> dict1
{'a': 12, 'b': 20, 'c': 33, 'd': None, 'f': 55}

我们也可以通过词典keys()方法循环遍历每个元素的键,也可以通过values()方法遍历每个元素的值。

>>> for i in dict1.keys():
    print(i)

    
a
b
c

>>> for k in dict1.values():
    print(k)

    
12
20
33
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容