Python入門(三)之字符串--列表--元組--字典--集合

作者:PyQuant
博客https://blog.csdn.net/qq_33499889
慕課https://mooc1-2.chaoxing.com/course/207443619.html


點贊、關注再看,養成良好習慣
Life is short, U need Python
初學Python,快來點我吧
在這裏插入圖片描述



1. 字符串

# 字符串定義
s = 'hello python'
s
'hello python'
# 類型和長度
type(s),len(s)
(str, 12)
# 索引
s[0],s[1],s[-1]
('h', 'e', 'n')
# 切片:前閉後開
s[0:5],s[:5],s[0:5:1]
('hello', 'hello', 'hello')
s[:],s[::1],s[::-1]
('hello python', 'hello python', 'nohtyp olleh')
s[0:5:2]
'hlo'
# 方法
print(dir(s))
['__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', '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']
# join--replace--zfill
s = 'hello python'
'*'.join(s),s.replace('o','-java-'),s.zfill(15)
('h*e*l*l*o* *p*y*t*h*o*n', 'hell-java- pyth-java-n', '000hello python')
# count--index--rindex--find--rfind
s = 'hello python'
s.count('o'),s.index('o'),s.rindex('o'),s.find('o'),s.rfind('o'),s.find('w')
(2, 4, 10, 4, 10, -1)
# capitalize--title--lower--upper
'hello python'.capitalize(),'hello python'.title(),'Hello Python'.upper(),'Hello Python'.lower()
('Hello python', 'Hello Python', 'HELLO PYTHON', 'hello python')
# strip--lstrip--rstrip
s = '****hello python**'
s.strip('*'),s.lstrip('*'),s.rstrip('*')
('hello python', 'hello python**', '****hello python')
# split--rsplit
s = 'hello python'
s.split('o'),s.rsplit('o')
(['hell', ' pyth', 'n'], ['hell', ' pyth', 'n'])
s = 'hello python'
s.split('o',1),s.rsplit('o',1)
(['hell', ' python'], ['hello pyth', 'n'])
# isalnum--isalpha--islower--isspace--istitle--isupper
s = 'Python123'
s.isalnum(),s.isalpha(),s.islower(),s.istitle(), s.isupper(),s.isspace()  
(True, False, False, True, False, False)
# isdecimal--isdigit--isnumeric
s_1 = '4'
s_1.isdecimal(),s_1.isdigit(),s_1.isnumeric()
(True, True, True)
s_2 = 'IV'
s_2.isdecimal(),s_2.isdigit(),s_2.isnumeric()
(False, False, False)
s_3 = '四'
s_3.isdecimal(),s_3.isdigit(),s_3.isnumeric()
(False, False, True)
# format
'I like {}.'.format('python'.title())
'I like Python.'
# 運算符運算:+ 和 *
s = 'python'
'Hello' + ' ' + s, s * 2
('Hello python', 'pythonpython')

2. 列表

# 列表定義
lst = [0,1,2,3,4]
lst
[0, 1, 2, 3, 4]
lst = list(range(5))
lst
[0, 1, 2, 3, 4]
# 類型和長度
type(lst),len(lst)
(list, 5)
# 索引
lst[0],lst[1],lst[-1]
(0, 1, 4)
# 切片
lst[0:4],lst[:4],lst[0:4:1]
([0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3])
lst[:],lst[::1],lst[::-1]
([0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [4, 3, 2, 1, 0])
lst[::2]
[0, 2, 4]
# 方法
print(dir(lst))
['__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']
# append---extend
lst = [0,1,2,3,4]
lst.append(5)
lst
[0, 1, 2, 3, 4, 5]
lst = [0,1,2,3,4]
lst.extend([5,6])
lst
[0, 1, 2, 3, 4, 5, 6]
lst = [0,1,2,3,4]
lst.append([5,6])
lst
[0, 1, 2, 3, 4, [5, 6]]
# remove---pop---del---clear
lst = [0,1,2,3,4]
lst.remove(4)
lst
[0, 1, 2, 3]
lst = [0,1,2,3,4]
lst.pop()
4
lst
[0, 1, 2, 3]
lst = [0,1,2,3,4]
lst.pop(3)
3
lst
[0, 1, 2, 4]
lst = [0,1,2,3,4]
lst.clear()
lst
[]
lst = [0,1,2,3,4]
del lst
lst
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-39-b5cada25ed2a> in <module>()
----> 1 lst


NameError: name 'lst' is not defined
# count---index---insert
lst = [1,4,2,3,1,2,3,2]
lst.count(2),lst.index(3)
(3, 3)
lst.insert(1,'python')
lst
[1, 'python', 4, 2, 3, 1, 2, 3, 2]
# sort---reverse
lst = [1,4,2,3,1,2,3,2]
lst.sort()
lst
[1, 1, 2, 2, 2, 3, 3, 4]
lst = [1,4,2,3,1,2,3,2]
lst.sort(reverse=True)
lst
[4, 3, 3, 2, 2, 2, 1, 1]
lst = [1,4,2,3,1,2,3,2]
lst.reverse()
lst
[2, 3, 2, 1, 3, 2, 4, 1]
# copy---deepcopy
lst = [1,2,[3,4]]
lst_1 = lst.copy()
lst,lst_1
([1, 2, [3, 4]], [1, 2, [3, 4]])
lst[0] = 10
lst
[10, 2, [3, 4]]
lst_1
[1, 2, [3, 4]]
lst[2][0] = 30
lst
[10, 2, [30, 4]]
lst_1
[1, 2, [30, 4]]
import copy
lst = [1,2,[3,4]]
lst_1 = copy.deepcopy(lst)
lst,lst_1
([1, 2, [3, 4]], [1, 2, [3, 4]])
lst[0] = 10
lst
[10, 2, [3, 4]]
lst_1
[1, 2, [3, 4]]
lst[2][0] = 30
lst
[10, 2, [30, 4]]
lst_1
[1, 2, [3, 4]]
# 運算符運算:+ 和 *
lst = [1,2,3,4]
lst + [3,4,5], lst * 2
([1, 2, 3, 4, 3, 4, 5], [1, 2, 3, 4, 1, 2, 3, 4])

3. 元組

# 元組的定義
t = (0, 1, 2, 3, 4)
t
(0, 1, 2, 3, 4)
t = tuple(range(5))
t
(0, 1, 2, 3, 4)
# 屬性和長度
type(t),len(t)
(tuple, 5)
# 索引
t = (0, 1, 2, 3, 4)
t[0],t[1],t[-1]
(0, 1, 4)
# 切片
t = (0, 1, 2, 3, 4)
t[0:4],t[:4],t[0:4:1]
((0, 1, 2, 3), (0, 1, 2, 3), (0, 1, 2, 3))
t = (0, 1, 2, 3, 4)
t[:],t[::1],t[::-1]
((0, 1, 2, 3, 4), (0, 1, 2, 3, 4), (4, 3, 2, 1, 0))
t = (0, 1, 2, 3, 4)
t[::2]
(0, 2, 4)
# 方法
t = (0, 1, 2, 3, 4)
print(dir(t))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
# count---index
t = (2, 1, 2, 4, 2)
t.count(2),t.index(2),t.index(4)
(3, 0, 3)
# 運算符運算:+ 和 *
t = (1, 2, 3, 4)
t + (4,5,6), t * 2
((1, 2, 3, 4, 4, 5, 6), (1, 2, 3, 4, 1, 2, 3, 4))

4. 字典

# 字典的定義: 鍵值對
d = {'a':10,'b':20,'c':30}
d
{'a': 10, 'b': 20, 'c': 30}
# 屬性和長度
d = {'a':10,'b':20,'c':30}
type(d),len(d)
(dict, 3)
# 索引
d = {'a':10,'b':20,'c':30}
d['b']
20
d['b'] = 200
d
{'a': 10, 'b': 200, 'c': 30}
# 切片----無序,無法切片(報錯)
d = {'a':10,'b':20,'c':30}
d[0:2]
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-70-84f0c84760eb> in <module>()
      1 # 切片----無序,無法切片(報錯)
      2 d = {'a':10,'b':20,'c':30}
----> 3 d[0:2]


TypeError: unhashable type: 'slice'
# 方法
d = {'a':10,'b':20,'c':30}
print(dir(d))
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
# keys---values---items
d = {'a':10,'b':20,'c':30}
d.keys(), d.values(),d.items()
(dict_keys(['a', 'b', 'c']),
 dict_values([10, 20, 30]),
 dict_items([('a', 10), ('b', 20), ('c', 30)]))
# update---pop---popitem---clear
d = {'a':10,'b':20,'c':30}
d.update({'d':40})
d
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
d = {'a':10,'b':20,'c':30}
d.pop('a')
10
d
{'b': 20, 'c': 30}
d = {'a':10,'b':20,'c':30}
d.popitem()
('c', 30)
d
{'a': 10, 'b': 20}
d = {'a':10,'b':20,'c':30}
d.clear()
d
{}
# fromkeys---get---setdefault
d = {'a':10,'b':20,'c':30}
d.fromkeys('b',200)
{'b': 200}
d
{'a': 10, 'b': 20, 'c': 30}
d = {'a':10,'b':20,'c':30}
d.get('b')
20
d
{'a': 10, 'b': 20, 'c': 30}
d = {'a':10,'b':20,'c':30}
d.get('d')
d
{'a': 10, 'b': 20, 'c': 30}
d = {'a':10,'b':20,'c':30}
d.get('d',1000)
1000
d
{'a': 10, 'b': 20, 'c': 30}
d = {'a':10,'b':20,'c':30}
d.setdefault('b')
20
d
{'a': 10, 'b': 20, 'c': 30}
d = {'a':10,'b':20,'c':30}
d.setdefault('d')
d
{'a': 10, 'b': 20, 'c': 30, 'd': None}
d = {'a':10,'b':20,'c':30}
d.setdefault('d',1000)
1000
d
{'a': 10, 'b': 20, 'c': 30, 'd': 1000}
# 運算符運算:+ 和 *  (不支持!)
d = {'a':10,'b':20,'c':30}
d + {'d':40}
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-93-440e989e5216> in <module>()
      1 # 運算符運算:+ 和 *  (不支持!)
      2 d = {'a':10,'b':20,'c':30}
----> 3 d + {'d':40}


TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

5. 集合

# 集合的定義
set_1 = {0,1,2,3,4}
set_1
{0, 1, 2, 3, 4}
set_1 = set(range(5))
set_1
{0, 1, 2, 3, 4}
{0,1,2,[3,4]}   # 列表不哈希對象
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-96-454c915f3447> in <module>()
----> 1 {0,1,2,[3,4]}   # 列表不哈希對象


TypeError: unhashable type: 'list'
{0,1,2,'python'},{0,1,2,(3,4)}
({0, 1, 2, 'python'}, {(3, 4), 0, 1, 2})
# 屬性和長度
type(set_1),len(set_1)
(set, 5)
# 索引、切片(因爲集合無序,所以不存在索引和切片)
set_1 = {0,1,2,3,4}
set_1[1]
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-99-0ab0b37cd7a6> in <module>()
      1 # 索引、切片(因爲集合無序,所以不存在索引和切片)
      2 set_1 = {0,1,2,3,4}
----> 3 set_1[1]


TypeError: 'set' object does not support indexing
# 方法
set_1 = {0,1,2,3,4}
print(dir(set_1))
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
# add---update---union
set_1 = {0,1,2,3,4}
set_1.add(5)
set_1
{0, 1, 2, 3, 4, 5}
set_1 = {0,1,2,3,4}
set_1.update({5,6})
set_1
{0, 1, 2, 3, 4, 5, 6}
set_1 = {0,1,2,3,4}
set_1.union({5,6})    # 返回新的集合
{0, 1, 2, 3, 4, 5, 6}
set_1                # 原集合不變
{0, 1, 2, 3, 4}
# remove---pop---discard---clear
set_1 = {0,1,2,3,4}
set_1.remove(3)
set_1
{0, 1, 2, 4}
set_1 = {0,1,2,3,4}
set_1.pop()
0
set_1
{1, 2, 3, 4}
set_1 = {0,1,2,3,4}
set_1.discard(3)
set_1
{0, 1, 2, 4}
set_1 = {0,1,2,3,4}
set_1.clear()
set_1
set()
# issubset---issuperset---isdisjoint
set_1 = {0,1,2,3,4}
set_2 = {2,3,4}
set_1.issubset(set_2),set_1.issuperset(set_2),set_1.isdisjoint(set_2),
(False, True, False)
# difference---intersection
set_1 = {0,1,2,3,4}
set_2 = {2,3,4}
set_1.difference(set_2),set_1.intersection(set_2)
({0, 1}, {2, 3, 4})
# copy
set_1 = {0,1,2,3}
set_2 = set_1.copy()
set_2
{0, 1, 2, 3}
# 運算符運算:+ 和 *  (不支持!)
set_1 = {0,1,2,3}
set_1 + {4,5}, set_1 * 2
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-113-2514aabca504> in <module>()
      1 # 運算符運算:+ 和 *  (不支持!)
      2 set_1 = {0,1,2,3}
----> 3 set_1 + {4,5}, set_1 * 2


TypeError: unsupported operand type(s) for +: 'set' and 'set'
# 不可哈希對象:列表、字典、集合
{0,1,2,[3,4]}
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-114-cb4dcd0ecaae> in <module>()
      1 # 不可哈希對象:列表、字典、集合
----> 2 {0,1,2,[3,4]}


TypeError: unhashable type: 'list'
{0,1,2,{'a':10,'b':20}}
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-115-d19d531386f5> in <module>()
----> 1 {0,1,2,{'a':10,'b':20}}


TypeError: unhashable type: 'dict'
{0, 1, 2, {3,4}}
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-116-f020c453e5b6> in <module>()
----> 1 {0, 1, 2, {3,4}}


TypeError: unhashable type: 'set'
# 可哈希對象:字符串,數,元組
{0,1,2,3},{0,1,2,'python'},{0,1,2,(3,4)}
({0, 1, 2, 3}, {0, 1, 2, 'python'}, {(3, 4), 0, 1, 2})
# 可變對象:列表 + 字典 + 集合
lst = [1,2,3,4]
lst[0] = 100

d = {'a':10,'b':20}
d['a'] = 1000

set_1 = {1,2,3,4}
set_1.add(5)

lst, d, set_1
([100, 2, 3, 4], {'a': 1000, 'b': 20}, {1, 2, 3, 4, 5})
# 不可變對象:字符串 + 元組
s = 'python'
s[0] = 'P'
s
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-119-64ca1193f222> in <module>()
      1 # 不可變對象:字符串 + 元組
      2 s = 'python'
----> 3 s[0] = 'P'
      4 s


TypeError: 'str' object does not support item assignment
t = (1,2,3,4)
t[0] = 100
t
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-120-f760b222adea> in <module>()
      1 t = (1,2,3,4)
----> 2 t[0] = 100
      3 t


TypeError: 'tuple' object does not support item assignment
# 但是,嵌套元組可變(事實上,相當於嵌套的可變對象發生改變)
t = (1,2,[3,4])
t[2][0] = 300     
t
(1, 2, [300, 4])

  • 寫作不易,切勿白剽
  • 博友們的點贊關注就是對博主堅持寫作的最大鼓勵
  • 持續更新,未完待續…

上一篇Python入門(二)之 Python的集成開發環境(IDE)
下一篇Python入門(四)之 循環語句—解析式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章