1. 程式人生 > >003-小白學python-for迴圈/字串/列表

003-小白學python-for迴圈/字串/列表

目錄

for迴圈/字串/列表

1for定義

for item in iteration:
    pass
s = 'hello world'
for i in s:
    print(i)

意義

item 是一個臨時變數,每遍歷一個成員就會被重新賦值
對物件的每一個成員,一個一個取出來,進行操作,而且自動捕獲stop

for與break

s = 'hello world'
for i in s:
    if i == 'o':
        break
    print(i)

for-else懸掛 break

for正常執行完成,就會執行else,被braek打斷就不會執行else
else不屬於迴圈當中,所以不能使用break continue

name = 'monday'
for i in name:
    if i == 'd':
        print('出現d')
        break
else:
    print('沒有出現d')

字串

建立字串,空格也算是一個字元

'' "" 三引號

下標訪問字串字元

正向從0開始,到len -1
反向從-1開始,到-len

s3 = 'sadasfafadf'
print(s3[10])
print(s3[-1])
print(s3[-4])
下標不能超過字串的長度減1 len() - 1,超過就會引發indexError
反向不能小於-len
print(s3[20])

切片,

步長(表示方向與取值長度)正向切片 0開始,到len-1,反向 -1 開始,到 -len
技巧:
先看步長,是正,從左到右,是負數,從右到左
start --> end 的方向一定要和step的方向一致
特殊切片:
不寫開頭表示從0開始,不寫結束表示到最後

s3 = 'sadasfafadf'
print(s3[10])
# print(s3[20]) #  超出報錯
print(s3[-1])    # 最後一個
print(s3[-4])
print(s3[0:3])
print(s3[1:3])
print(s3[1:8:2])
print(s3[0:])
print(s3[2:])
print(s3[:])
print(s3[-3:-7:-1])
# print(s3[-3:-7])
print(s3[-7:-3:2]) # 一般不這樣寫(步長為正,start end直接)
print(s3[-1:-7:-2])
print(s3[::-1])
print(s3[0:-1])

字串操作

查詢

.find()
.rfind()
.index()
.rindex()

s = 'hello world'
print(s.find('o'))  # 4
print(s.rfind('o'))  # 從右找,但是序號從左計數
print(s.index('l'))  # 2
print(s.rindex('l'))  # 9

計數

.count()

print(s.count('o')) 

開頭結尾

.startswith()
.endswith()

print(s.startswith('hello'))  # True
print(s.endswith('ld'))  # True

長度
len()

print(len(s))  # 11

列表

定義

lst = []
lst = list()
lst = [1, 2, 3]
特點:有序,下標訪問,儲存任何的資料型別

增加

.append() 只能是一個引數
.insert(index, value) 指定index位置index插入
.extend(iter) 傳入一個可迭代物件

# lst1 = [1, 2, 3, 4, 5]
lst1 = [i for i in range(1, 6)]  # 一般列表建立可以使用
lst1.append(6)
lst1.insert(2, 10)
lst1.extend([9, 9, 9])
print(lst1)

刪除

.pop()
.pop(index) # 涉及到index與value都要考慮是否超出與沒有該值的情況
.remove(value)

# del刪除
lst2 = ['name', 'age', 'length', 'good', 'boy', 'love']
del lst2[0]
print(lst2)
# pop()  有返回值
remove_value = lst2.pop()
print(remove_value, lst2, '******')
# pop(index)
remove_value1 = lst2.pop(1)
print(remove_value1, lst2, '++++++')
# remove()
print(lst2.remove('boy'))  # 不能刪除沒有的值,而且沒有返回值

主要是通過索引來改
lst[index] = newValue

lst[index],for 迴圈

巢狀列表

多維列表(一般二維三維)
lst = [[], [], [], []]
增刪改查:原則
1。找到物件
2。利用下標
有10個球分別3紅、3藍、4白,現需要將這10個球隨機放入這3個盒子,要求每個盒子至少有一個白球,請用程式實現

import random
lst = [[], [], []]
s = ['r', 'r', 'r', 'b', 'b', 'b', 'w']
# 初始化,保證每個裡面有一個w
for i in lst:
    i.append('w')
print(lst)
# 然後就是隨便新增進去
for item in s:
    index = random.randint(0, 2)
    lst[index].append(item)
print(lst)