Day2-數據類型

數據類型與內置方法

數據類型

  • 數字
  • 字符串
  • 列表
  • 字典
  • 元組
  • 集合

字符串

1.用途

用來描述某個物體的特征:姓名,性別,愛好等

2.定義方式

變量名 = '字符串'
如:name = 'huazai'

3.常用操作和內置方法


1.按索引取值:(只能取值,不能改變值)通過字符串的索引值可以取到對應位置的字符>>> name = 'huazai'>>> name[1]'u'>>> name[-1]'i'2.切片通過索引值的范圍進行取值>>> name = 'huazai'>>> name[0:3]  #按范圍取值,默認步長為1,正向'hua'>>> name[-1:-4:-1]  #逆向取值'iaz'>>> name[0:5:2]  #按步長取值'haa'3.長度函數len()計算長度>>> name = 'huazai'  #實質是調用name.__len__()>>> len(name)6
4.成員運算in 和not in>>> name = 'huazai'>>> 'a' in nameTrue>>> 'f' not in nameTrue>>> 'f' in nameFalse
5.移除空白strip、lstrip、rstrip默認移除字符串開頭和結尾處的空白>>> str1 = '   hua zai   '>>> print(str1.strip())hua zai#字符串中間的空白并不會移除,常用在與讓用戶輸入內容時,對其進行處理。括號內可以指定移除的字符串>>> str1 = '***hua zai****'>>> print(str1.strip('*'))hua zai>>> print(str1.lstrip('*'))hua zai****>>> print(str1.rstrip('*'))***hua zai
6.切分splist將字符串按某種定義的符號進行拆分成列表>>> str1 = 'root:x:0:0::/root:/bin/bash'>>> print(str1.split(':'))['root', 'x', '0', '0', '', '/root', '/bin/bash']>>> print(str1.rsplit(':',1)) #從右開始切分,只切分一次['root:x:0:0::/root', '/bin/bash']
7.lower,upper將字母變成大小寫>>> str1 = 'huazai'>>> print(str1.upper())HUAZAI>>> str2 = 'HuaZai'>>> print(str2.lower())huazai
8.startswith,endswith判斷字符串以什么開頭、什么結尾>>> str1 = 'huazai123'>>> print(str1.startswith('hua'))True>>> print(str1.startswith('123'))False>>> print(str1.endswith('123'))True
9.format的三種玩法常用在輸出的時候,不需要根據占位符的位置順序指定變量的順序,方便,也是常用的方法。>>> print('my name is {name},i am {age} old'.format(age=18,name='huazai'))my name is huazai,i am 18 old
10.join將字符串已某種符號隔開,可迭代的對象必須為字符串>>> print('*'.join(['my','name','is','huazai']))my*name*is*huazai11.replace將字符串1替換成字符串2,>>> str1 = 'huazai'>>> str2 = 'zai123'>>> print(str1.replace('zai',str2))huazai123>>> print(str1) #源字符串并不會被改變,因為字符串是不可變對象huazai可以指定替換次數>>> str1 = 'huazaizaizaizai'>>> str2 = 'zai123'>>> print(str1.replace('zai',str2,2))huazai123zai123zaizai
12.isdigit判斷一個字符串是否是數字>>> a = 'huazai'>>> print(a.isdigit())False
其他操作(了解部分):13.find,rfind,index,rindex,count
find>>> str1 = 'huazai'>>> print(str1.find('a',1,5))2>>> print(str1.find('l',1,5)) #不存在返回-1-1
index>>> print(str1.index('a'))2>>> print(str1.index('l')) #不存在會報錯Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: substring not found
count>>> print(str1.count('a'))2
14.center,ljust,rjust,zfill>>> str1 = 'huazai'>>> print(str1.center(50,'*'))**********************huazai**********************>>> print(str1.ljust(50,'*'))huazai********************************************>>> print(str1.rjust(50,'*'))********************************************huazai>>> print(str1.rjust(50))huazai>>> print(str1.zfill(50))00000000000000000000000000000000000000000000huazai
15.expandtabs將tab鍵轉換成幾個空格>>> str1 = 'hua\tzai' >>> print(str1)hua     zai>>> print(str1.expandtabs())hua     zai>>> print(str1.expandtabs(1))hua zai
16.captalize,swapcase,title>>> str1 = 'huA Zai'>>> print(str1.capitalize())Hua zai>>> print(str1.swapcase())HUa zAI>>> print(str1.title())Hua Zai
17.is數字系列#在python3中num1=b'4' #bytesnum2=u'4' #unicode,python3中無需加u就是unicodenum3='四' #中文數字num4='Ⅳ' #羅馬數字#isdigt:bytes,unicodeprint(num1.isdigit()) #Trueprint(num2.isdigit()) #Trueprint(num3.isdigit()) #Falseprint(num4.isdigit()) #False#isdecimal:uncicode#bytes類型無isdecimal方法print(num2.isdecimal()) #Trueprint(num3.isdecimal()) #Falseprint(num4.isdecimal()) #False#isnumberic:unicode,中文數字,羅馬數字#bytes類型無isnumberic方法print(num2.isnumeric()) #Trueprint(num3.isnumeric()) #Trueprint(num4.isnumeric()) #True
18.is其他print('===>')name='huazai'print(name.isalnum()) #字符串由字母或數字組成print(name.isalpha()) #字符串只由字母組成print(name.isidentifier())print(name.islower())print(name.isupper())print(name.isspace())print(name.istitle())

列表

1.用途

用來描述同一屬性可以有多種,如:愛好,課程等

2.定義方式

habbies=['basketball','read','movie','music']
或者
L= list('basketball','read','movie','music')

3.常用操作和內置方法

1.必會操作按索引存取值>>> habbies=['basketball','read','movie','music']>>> habbies[0]'basketball'>>> habbies[-1]'music'>>> habbies[2]='girls'>>> habbies['basketball', 'read', 'girls', 'music']切片(與字符串類似)>>> habbies=['basketball','read','movie','music']>>> habbies[0:3]['basketball', 'read', 'movie']>>> habbies[0:4:2]['basketball', 'movie']>>> habbies[-1:0:-1]['music', 'movie', 'read']長度len>>> habbies=['basketball','read','movie','music']>>> len(habbies)4成員運算in、not in>>> habbies=['basketball','read','movie','music']>>> habbies=['basketball','read','movie','music']>>> 'read' in habbiesTrue>>> 'girl' not in habbiesTrue追加append>>> habbies=['basketball','read','movie','music']>>> habbies.append('girls')>>> habbies['basketball', 'read', 'movie', 'music', 'girls']刪除del、remove>>> habbies['basketball', 'read', 'movie', 'music', 'girls']>>> habbies.pop()'girls'>>> habbies>>>['basketball', 'read', 'movie', 'music']>>>habbies=['basketball','read','movie','music']>>>habbies.remove('movie')>>>print(habbies)>>>['basketball', 'read', 'music']循環:habbies=['basketball','read','movie','music']1. for item in habbies:print(item)2.i=0while i <len(habbies):print(habbies[i])i+=1
熟悉內置方法:
# pop:從尾部刪除元素
habbies.pop()
habbies.pop()# extend:增加元素
habbies.extend('girls')# index:獲取元素的索引值
print(habbies.index('basketball'))
# count:統計元素
print(habbies.count('read'))
# clear:清空列表
habbies.clear()
# copy:復制一份列表
L = habbies.copy()
print(L)
# insert:指定位置插入元素
habbies.insert(1,'girls')
# reverse:反轉列表所有元素的順序
habbies.reverse()
# sort:元素排序
print(habbies.sort())

字典

1.作用

將多個值以key-value的形式保存,取值速度快

2.定義

其中key是不可變類型(數字,字符串,元組),value可以是任意類型
user_info = {'name':'huazai','sex':'male','age':'18'}
或者
user_info = dict(name='huazai',sex='male',age=18)
或者
{}.fromkeys(('name','sex','age'),None)

3. 常用操作

#常用操作
#存取值,按key存取
user_info = {'name':'huazai','sex':'male','age':'18'}
print(user_info['name'])
user_info['habbies']='girls'
print(user_info)#長度
print(len(user_info))
print(user_info.__len__())#成員運算in、not inprint('name' in user_info)
print('habbies' not in user_info)# 刪除
del user_info['name']
user_info.pop('name')# 鍵值對操作 keys() value()  鍵值對items
print(user_info.keys())
print(user_info.values())
print(user_info.items())# 循環
for key in user_info:print(key,user_info[key])# 了解方法
# fromkey
print(user_info.fromkeys('name'))# clear 清空字典
user_info.clear()#setdefault 如果key存在不會被覆蓋,見練習二
user_info.setdefault()# update 更新
d = {'name':'egon'}
user_info.update(d)
print(user_info)# get 不存在返回None
print(user_info.get('habbies'))# copy
L = user_info.copy()
print(L)

4.練習

#練習
#1 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],將所有大于 66 的值保存至字典的第一個key中,將小于 66 的值保存至第二個key的值中#即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
L = [11,22,33,44,55,66,77,88,99,90]
d ={'k1':[],'k2':[]}
for i in L:if i > 66:d['k1'].append(i)else:d['k2'].append(i)
print(d)'''
2 統計s='hello alex alex say hello sb sb'中每個單詞的個數結果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
'''
s = 'hello alex alex say hello sb sb'
L = s.split(" ")
print(L)
d = {}
for key in L:count = L.count(key)d.setdefault(key,count)
print(d)

元組

1. 作用:

# 存儲多個不可變的值,主要用來只讀的數據

2. 定義

# t = (1,2,3,4,5)
# t = tuple(1,2,3,4,5)

3. 常用操作和內置方法

# 掌握
#  按索引取值,同列表一樣,但是只能取值
t = (1,2,3,'huazai')
print(t[2])
print(t[-1])# 切片,也同列表操作
print(t[1:3])
print(t[-1:0:-1])#長度
print(len(t))
print(t.__len__())#成員運算 in、not in
print('huazai' in t)#循環
for i in t:print(i)# 內置方法
# index 元素索引位置
print(t.index(1))# count 元素統計
print(t.count('huazai'))

集合

1. 作用

去重,關系運算,

2. 定義

集合:可以包含多個元素,用逗號分割,
集合的元素遵循三個原則:
1:每個元素必須是不可變類型(可hash,可作為字典的key)
2: 沒有重復的元素
3:無序
s1 = {1,2,2,3,4,5,6}
s2 = {4,5,6,7,8,9}

3.常用操作和內置方法

#1、長度len
# print(len(s1))
#2、成員運算in和not in
# print(2 in s1)
#3、|合集
print(s1 | s2)
#4、&交集
print(s1 & s2)
#5、-差集
print(s1 - s2)
#6、^對稱差集
print(s1 ^ s2)
#7、==
print(s1 == s2)
#8、父集:>,>=
print(s1 > s2)
#9、子集:<,<=
print(s1 < s2)

4. 練習

'''一.關系運算有如下兩個集合,pythons是報名python課程的學員名字集合,linuxs是報名linux課程的學員名字集合pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}linuxs={'wupeiqi','oldboy','gangdan'}1. 求出即報名python又報名linux課程的學員名字集合2. 求出所有報名的學生名字集合3. 求出只報名python課程的學員名字4. 求出沒有同時這兩門課程的學員名字集合
'''
# pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
# linuxs={'wupeiqi','oldboy','gangdan'}
# print(pythons & linuxs)
# print(pythons | linuxs)
# print(pythons - linuxs)
# print(pythons ^ linuxs)
'''
二.去重1. 有列表l=['a','b',1,'a','a'],列表元素均為可hash類型,去重,得到新列表,且新列表無需保持列表原來的順序2.在上題的基礎上,保存列表原來的順序3.去除文件中重復的行,肯定要保持文件內容的順序不變4.有如下列表,列表元素為不可hash類型,去重,得到新列表,且新列表一定要保持列表原來的順序l=[{'name':'egon','age':18,'sex':'male'},{'name':'alex','age':73,'sex':'male'},{'name':'egon','age':20,'sex':'female'},{'name':'egon','age':18,'sex':'male'},{'name':'egon','age':18,'sex':'male'},
]  '''l = ['a','b',1,'a','a']
print(set(l))
L= []
for i in l:if i not in L:L.append(i)
print(L)

轉載于:https://blog.51cto.com/ronghuachen/2050442

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391869.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391869.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391869.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

嵌套路由

父組件不能用精準匹配&#xff0c;否則只組件路由無法展示 轉載于:https://www.cnblogs.com/dianzan/p/11308146.html

leetcode 992. K 個不同整數的子數組(滑動窗口)

給定一個正整數數組 A&#xff0c;如果 A 的某個子數組中不同整數的個數恰好為 K&#xff0c;則稱 A 的這個連續、不一定獨立的子數組為好子數組。 &#xff08;例如&#xff0c;[1,2,3,1,2] 中有 3 個不同的整數&#xff1a;1&#xff0c;2&#xff0c;以及 3。&#xff09; …

從完整的新手到通過TensorFlow開發人員證書考試

I recently graduated with a bachelor’s degree in Civil Engineering and was all set to start with a Master’s degree in Transportation Engineering this fall. Unfortunately, my plans got pushed to the winter term because of COVID-19. So as of January this y…

微信開發者平臺如何編寫代碼_編寫超級清晰易讀的代碼的初級開發者指南

微信開發者平臺如何編寫代碼Writing code is one thing, but writing clean, readable code is another thing. But what is “clean code?” I’ve created this short clean code for beginners guide to help you on your way to mastering and understanding the art of c…

【轉】PHP面試題總結

PHP面試總結 PHP基礎1&#xff1a;變量的傳值與引用。 2&#xff1a;變量的類型轉換和判斷類型方法。 3&#xff1a;php運算符優先級&#xff0c;一般是寫出運算符的運算結果。 4&#xff1a;PHP中函數傳參&#xff0c;閉包&#xff0c;判斷輸出的echo&#xff0c;print是不是函…

Winform控件WebBrowser與JS腳本交互

1&#xff09;在c#中調用js函數 如果要傳值&#xff0c;則可以定義object[]數組。 具體方法如下例子&#xff1a; 首先在js中定義被c#調用的方法: function Messageaa(message) { alert(message); } 在c#調用js方法Messageaa private void button1_Click(object …

從零開始擼一個Kotlin Demo

####前言 自從google將kotlin作為親兒子后就想用它擼一管app玩玩&#xff0c;由于工作原因一直沒時間下手&#xff0c;直到項目上線后才有了空余時間&#xff0c;期間又由于各種各樣煩人的事斷了一個月&#xff0c;現在終于開發完成項目分為服務器和客戶端&#xff1b;服務器用…

移動平均線ma分析_使用動態移動平均線構建交互式庫存量和價格分析圖

移動平均線ma分析I decided to code out my own stock tracking chart despite a wide array of freely available tools that serve the same purpose. Why? Knowledge gain, it’s fun, and because I recognize that a simple project can generate many new ideas. Even t…

敏捷開發創始人_開發人員和技術創始人如何將他們的想法轉化為UI設計

敏捷開發創始人by Simon McCade西蒙麥卡德(Simon McCade) 開發人員和技術創始人如何將他們的想法轉化為UI設計 (How developers and tech founders can turn their ideas into UI design) Discover how to turn a great idea for a product or service into a beautiful UI de…

在ubuntu怎樣修改默認的編碼格式

ubuntu修改系統默認編碼的方法是&#xff1a;1. 參考 /usr/share/i18n/SUPPORTED 編輯/var/lib/locales/supported.d/* gedit /var/lib/locales/supported.d/localgedit /var/lib/locales/supported.d/zh-hans如&#xff1a;more /var/lib/locales/supported.d/localzh_CN GB18…

JAVA中PO,BO,VO,DTO,POJO,Entity

https://my.oschina.net/liaodo/blog/2988512轉載于:https://www.cnblogs.com/dianzan/p/11311217.html

【Lolttery】項目開發日志 (三)維護好一個項目好難

項目的各種配置開始出現混亂的現象了 在只有一個人開發的情況下也開始感受到維護一個項目的難度。 之前明明還好用的東西&#xff0c;轉眼就各種莫名其妙的報錯&#xff0c;完全不知道為什么。 今天一天的工作基本上就是整理各種配置。 再加上之前數據庫設計出現了問題&#xf…

leetcode 567. 字符串的排列(滑動窗口)

給定兩個字符串 s1 和 s2&#xff0c;寫一個函數來判斷 s2 是否包含 s1 的排列。 換句話說&#xff0c;第一個字符串的排列之一是第二個字符串的子串。 示例1: 輸入: s1 “ab” s2 “eidbaooo” 輸出: True 解釋: s2 包含 s1 的排列之一 (“ba”). 解題思路 和s1每個字符…

靜態變數和非靜態變數_統計資料:了解變數

靜態變數和非靜態變數Statistics 101: Understanding the different type of variables.統計101&#xff1a;了解變量的不同類型。 As we enter the latter part of the year 2020, it is safe to say that companies utilize data to assist in making business decisions. F…

代碼走查和代碼審查_如何避免代碼審查陷阱降低生產率

代碼走查和代碼審查Code reviewing is an engineering practice used by many high performing teams. And even though this software practice has many advantages, teams doing code reviews also encounter quite a few code review pitfalls.代碼審查是許多高性能團隊使用…

Zabbix3.2安裝

一、環境 OS: CentOS7.0.1406 Zabbix版本: Zabbix-3.2 下載地址: http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm MySQL版本: 5.6.37 MySQL: http://repo.mysql.com/mysql-community-release-el7-5.noarch.r…

Warensoft Unity3D通信庫使用向導4-SQL SERVER訪問組件使用說明

Warensoft Unity3D通信庫使用向導4-SQL SERVER訪問組件使用說明 (作者:warensoft,有問題請聯系warensoft163.com) 在前一節《warensoft unity3d通信庫使用向導3-建立WarensoftDataService》中已經說明如何配置Warensoft Data Service&#xff0c;從本節開始&#xff0c;將說明…

01-gt;選中UITableViewCell后,Cell中的UILabel的背景顏色變成透明色

解決方案有兩種方法一 -> 新建一個UILabel類, 繼承UILabel, 然后重寫 setBackgroundColor: 方法, 在這個方法里不做任何操作, 讓UILabel的backgroundColor不發生改變.寫在最后, 感謝參考的出處:不是謝志偉StackOverflow: UITableViewCell makes labels background clear whe…

leetcode 703. 數據流中的第 K 大元素(堆)

設計一個找到數據流中第 k 大元素的類&#xff08;class&#xff09;。注意是排序后的第 k 大元素&#xff0c;不是第 k 個不同的元素。 請實現 KthLargest 類&#xff1a; KthLargest(int k, int[] nums) 使用整數 k 和整數流 nums 初始化對象。 int add(int val) 將 val 插…

不知道輸入何時停止_知道何時停止

不知道輸入何時停止In predictive analytics, it can be a tricky thing to know when to stop.在預測分析中&#xff0c;知道何時停止可能是一件棘手的事情。 Unlike many of life’s activities, there’s no definitive finishing line, after which you can say “tick, I…