Python中的列表

序列是Python中最基本的數據結構。序列中的每一個元素都分配一個數字 - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推。
1.列表
數組:存儲同一種數據類型的集合 scores = [12,23,45]
列表(打了激素的數組):能夠存儲任意數據類型mysql

list = [1,1.2,True,'westos']
print(list,type(list))
與字符串的索引同樣,列表索引從0開始。列表能夠進行截取、組合等。sql

Python中的列表
#列表裏面也能夠嵌套列表
list2 = [1,2,3,4,[1,1.2,True,'westos']]
print(list2,type(list2))
Python中的列表
Python中的列表數組

2.列表的特性數據結構

#索引
#正向索引
service = ['http','ftp','ssh']
print(service[0])
#反向索引
print(service[-1])
Python中的列表
#切片
print(service[::-1]) # 列表元素序列反轉
print(service[1:]) #列表中除了第一個元素以外的元素
print(service[:-1]) # 列表中除了最後一個元素以外的元素
Python中的列表
#重複
print(service * 3) #重複三次
['http', 'ftp', 'ssh', 'http', 'ftp', 'ssh', 'http', 'ftp', 'ssh'] 生成的新列表
#鏈接
service1 = ['mysql','firewalld']
print(service + service1)
Python中的列表
#成員操做符
in #判斷元素是否屬於該列表 屬於爲真 不屬於爲假
not in #判斷元素是否不屬於該列表 屬於爲真 不屬於爲假
print('firewalld' in service) 判斷firewalld是不是列表中的元素
print('ftp' in service)
print('mysql' not in service) app

假定有下面這樣的列表:
names = ['fentiao', 'fendai', 'fensi', 'apple']
輸出結果爲:'I have fentiao, fendai, fensi and apple.'dom

print('I have ' + ','.join(names[:-1]) + ' and ' + names[-1])ssh

題目:輸入某年某月某日(yyyy-MM-dd),判斷這一天是這一年的第幾天?
1.cal = input('請輸入日期 yyyy-MM-dd:')
date = cal.split('-') #拆分日期
year = int(date[0])
month = int(date[1])
day = int(date[2])
arr = [0,31,28,31,30,31,30,31,31,30,31,30,31]
num = 0
if ((year % 4 ==0) and (year % 100 !=0)
or (year % 400== 0)):
arr[2] = 29
for i in range(1,len(arr)):
if month > i:
num += arr[i]
else:
num += day
break
print('天數:',num)ide

2.date=input('請輸入日期: ')
date1=date.split('-')
year=int(date1[0])
mon=int(date1[1])
day=int(date1[2])
k=0
list1=[0,31,28,31,30,31,30,31,31,30,31,30,31]
list2=[0,31,29,31,30,31,30,31,31,30,31,30,31]
if (year%400 == 0 or (year%4 == 0 and year%100 != 0)) :
for i in list2[:mon] :
k+=i
print('第%d 天' %(k+day))
else :
for i in list1[:mon] :
k+=i
print('第%d 天' %(k+day))
Python中的列表3d

列表元素的增長
service = ['http','ftp','ssh']blog

#append():追加一個元素到列表
service.append('firewalld')
print(service)

#extend():拉伸 追加多個元素到列表中
service.extend(['mysql','nfs'])
print(service)

#insert() 在指定索引處插入元素
service.insert(1,'https')
print(service)

#remove:刪除列表元素
service = ['http','ftp','ssh']
#a = service.remove('ftp')
#print(a)
#print(service)

#從內存中刪除一個數據
del service[1]
print(service)
service = ['ftp','http','http','ssh','ftp','ssh','ftp','ssh']

#查看元素在列表中出現的次數
print(service.count('ftp'))

#查看指定元素的索引值(能夠指定索引範圍)
print(service.index('ssh'))
print(service.index('ssh',4,7))
import random

列表元素的排序 # 默認是按照Ascii碼進行排序的
li = list(range(100))
print(li)
random.shuffle(li)
print(li)

Python包含如下方法:

Python中的列表

相關文章
相關標籤/搜索