python的簡單說明

# 介紹列表、元組、字典、序列的用法


# 列表 ---類似C++的vector,不定長數組
# 添加 mylist.append(x)   刪除 del mylist[n]    排序 mylist.sort()
n = int(input())
mylist = []  # 初始化
for i in range(0, n):
    x = int(input())
    mylist.append(x)  # 添加列表元素
print('列表元素爲:', end='')
print(mylist)
print('列表經過排序之後:', end='')
mylist.sort()  # 列表排序
for i in mylist:
    print(i, end=' ')
print('\n刪除mylist[1]這個元素後:',end='')
del mylist[1]  # 刪除列表元素
for i in range(0,len(mylist)):  # range爲左閉右開
    print(mylist[i], end=' ')
print('\n列表的複製:',end='')
newmylist = mylist
print(newmylist)
print('-------------------------------')

# 元組---他可以將列表以及元素混合封裝在一起,是不可改變的
mytuple = (1, 2, (4, 5))
print('元組元素爲:',end='')
print(mytuple)
newtuple = (0, mytuple)
print('新元組元素爲:', end='')
print(newtuple)
print('The newtuple[1][2][0] is:{}'.format(newtuple[1][2][0]))
print('-------------------------------')

# 序列---主要用於切片操作
# 其中字符串,列表,元組都可以看作序列,並進行切片操作
# string[:]代表整個序列,string[2:5]左閉右開,string[2:-1]其中-1代表最後一個元素,左閉右開就不包括,-2倒數第二
# mylist[0:-1:2],開頭到結尾,且步長爲2,第一個冒號不可缺省,其餘都可以缺省,缺前者就從開頭開始,後者就到結尾結束

string = 'Never say never!'
mylist = [5, 9, 4, 2, 5, 0]
print('The outcome of string[0:5] is: ', end=' ')
for i in string[0:5]:
    print(i, end='')
print('\nThe answer of mylist[:-1:2] is: ', mylist[:-1:2])
print('-------------------------------')

# 字典---相當於c++中的map,是鍵與值的對應 key: value
cnt = {'小米': 'Mi', '華爲': 'HuaWei'}
for name, loge in cnt.items():  # 將每一種映射輸出
    print('The Chinese name is: {} and the loge is:{} '.format(name, loge))
cnt['歐珀'] = 'oppo'  # 添加映射
string = '歐珀'
print('The Chinese name is: {} and the loge is:{} '.format(string, cnt[string]))
print('-------------------------------')

# 集合---和C++中set一直,多個重複元素,只儲存一個
# 聲明: myset = set([])   添加 myset.add(x)   刪除 myset.remove(x)
# 判斷是否存在 if x in myset:    取交集 myset&yourset
# 判斷是否包含 myset.issuperset(yourset) 返回bool     複製 yourset = myset.copy()

myset = set(['Mi', 'Huawei', 'Vivo'])
yourset = set(['Apple'])
string = 'Oppo'
if string not in myset:
    myset.add(string)
    myset.add(string)  # 添加兩次也只添加了一個
    print('Myset is:', myset)
else:
    print('It already in container.')
yourset = myset.copy()  # 複製時覆蓋了原來的apple
print('Yourset is: ', end=' ')
for i in yourset:
    print(i, end=' ')
if myset.issuperset(yourset):  # 相等時同樣返回True
    print('\nI\'m the father.')
else:
    print('You\'re the brother.')
yourset.remove(string)
print('The same of us: ', myset & yourset)

 

 

 

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