Python: 學習系列之三:基礎介紹二

對象的布爾值

"""
    以下對象的布爾值爲False, 其他的對象都爲True
"""
a = bool()  # 默認值爲False
a = bool(False)  #
a = bool("")  # 空字符串
a = bool(None)  #
a = bool([])  # 空列表
a = bool(())  # 空元組
a = bool({})  # 空字典
print(a)

if 18 and 'python':
    print('18 is True,"python" is True')

三目運算符

"""
    這點真難用
    Python語言不像Java、JavaScript等這些語言有類似:
    判段的條件?條件爲真時的結果:條件爲假時的結果
    這樣的三目運算,但是Python也有自己的三目運算符:   
    條件爲真時的結果 if 判段的條件 else 條件爲假時的結果

"""
scoreA = 29
scoreB = 20
result = 'A大於B' if scoreA > scoreB else 'A小於B'
print(result)

# 三目運算符寫法
print(x if(x>y) else y)

循環語句:只有while 和 for-in

while True:
    word = input("請輸入一個單詞:")
    if not word:
        break
    print('輸入的單詞是:', word)

# 遍歷列表
for item in ['a', 'b', 'c']:
    print(item)

# 遍歷列表, 這裏只能打印出a, b,不能打印出c
a = ['a', 'b', 'c']
for item in a:
    if item == 'b':
        a.remove(item)
    print(item)

# 遍歷列表, 這裏只能打印出a, b,c
# 這裏如果對列表進行修改操作,最好是先通過切片操作生成一份序列的拷貝
a = ['a', 'b', 'c']
for item in a[:]:
    if item == 'b':
        a.remove(item)
    print(item)

# 遍歷列表 [(0, 'a'), (1, 'b'), (2, 'c')]
for index, item in enumerate(['a', 'b', 'c']):
    print(index, item)

# 遍歷列表 [(1, 'a'), (2, 'b'), (3, 'c')]
for index, item in enumerate(['a', 'b', 'c'], 1):
    print(index, item)

# 遍歷元組
for item in ('a', 'b', 'c'):
    print(item)

# 遍歷字典 [('name', 'cong'), ('age', 20)]
for key, value in {'name': 'cong', 'age': 20}.items():
    print(key, value)

循環語句中的break-else

"""
    只有循環正常結束時,下面的語句纔會被執行
"""
for item in range(10):
    print(item)
else:
    print('所有的元素都遍歷了,沒有遇到break')

for item in range(10):
    if item == 8:
        break
    print(item)
else:  
    print('遇到break了,這條語句不會被執行')

 Zip方法的使用

a = ['a', 'b', 'c']
b = [1, 2, 3]
c = ['x', 'y', 'z', 'xx']  # 如果幾個可迭代對象的長度不同,較長的對象會被截斷,也就是說'xx'不會被用到
print(zip(a, b, c))  # <zip object at 0x000002AB25A68808>
print(list(zip(a, b, c)))  # [('a', 1, 'x'), ('b', 2, 'y'), ('c', 3, 'z')] 列表中的元素都是元組

for x, y, z in zip(a, b, c):
    print(x, y, z)

"""
    使用zip(*)對zip對象解壓縮
"""
d = zip(a, b, c)

print(list(zip(*d)))  # [('a', 'b', 'c'), (1, 2, 3), ('x', 'y', 'z')]

a2, b2, c2 = zip(*Ld)
print(a2, b2, c2)  # ('a', 'b', 'c') (1, 2, 3) ('x', 'y', 'z')
print(list(a2), list(b2), list(c2))  # ['a', 'b', 'c'] [1, 2, 3] ['x', 'y', 'z']

迭代器

"""
    只有zip纔是一個迭代器,列表和元組都不是,迭代器只能遍歷一次,遍歷後迭代器就空了,取不出來任何東西
"""

x = [1, 2]
# print(next(x))  # TypeError: 'list' object is not an iterator
y = (1, 2)
# print(next(y))  # TypeError: 'tuple' object is not an iterator

x = ["a", "1"]
y = ["b", "2"]
z = zip(x, y)

print(next(z))  # ('a', 'b')
print(next(z))  # ('1', '2')
# print(next(z))  # Error: print(next(z)) StopIteration
print(list(z))  # [] , 空的

 

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