列表

1.列表是Python中使用最频繁的数据类型 
2.列表可以完成大多数集合类的数据结构实现。 
3.列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套) 
4.和字符串一样,列表同样可以被索引和截取,列表被截取后返回一个包含所需元素的新列表 
5.List内置了有很多方法,例如append( )、pop()等等 
6.List可以使用+操作符进行拼接 
7.[注意]与Python字符串不一样的是,列表中的元素是可以改变。

列表的操作

1.索引,切片,加,乘,检查成员 
2.增加、删除、连接分割、排序倒序

list1=[1,2,3.0,4,5.0]
list2=['6','7','8','8','8']
list3=['One','Two','Three']
list4=[1,2,3]
print(len(list1))
print(list2.count('8'))
print(list1[0])
print(list1[-1])
print(list1[1:3])
print(list1[1:])
print(list1*2)
print(list1+list2)

if(1 in list1):
    print("1在列表list1中")

print('list1中最大元素对应下标为{0}'.format(list1.index(max(list1))))
print([list1,list2,list3])
##增加
list1.append(6)
list1.insert(2,2.5)
list1.extend([7,8])
print(list1)
##减小
del list1[2],list1[5]
list1.remove(7) #删除具体的值
pop_value=list1.pop(5)
print('pop_value={0}'.format(pop_value))
print(list1)
##连接与分割
join_list='--'.join(list2)  #join只能了解全是字符串的列表
print(join_list)
split_list=join_list.split('--',2)  #最后一个数字代表分割的次数,如果想全部分割则使用-1(默认)
print(split_list)

list1.reverse() #反向
print(list1)
list1.sort()    #排序
print(list1)

list_copy=list1.copy() 返回列表的浅复制,等于a[:]

输出结果

5
3
1
5.0
[2, 3.0]
[2, 3.0, 4, 5.0]
[1, 2, 3.0, 4, 5.0, 1, 2, 3.0, 4, 5.0]
[1, 2, 3.0, 4, 5.0, '6', '7', '8', '8', '8']
1在列表list1中
list1中最大元素对应下标为4
[[1, 2, 3.0, 4, 5.0], ['6', '7', '8', '8', '8'], ['One', 'Two', 'Three']]
[1, 2, 2.5, 3.0, 4, 5.0, 6, 7, 8]
pop_value=8
[1, 2, 3.0, 4, 5.0]
6--7--8--8--8
['6', '7', '8--8--8']
[5.0, 4, 3.0, 2, 1]
[1, 2, 3.0, 4, 5.0]

元组

元组与列表的区别,元组它的关键是不可变性,元组提供了一种完整的约束。 
1.[注意]元组(tuple)与列表类似,不同之处在于元组的元素不能修改 
2.元组写在小括号(())里,元素之间用逗号隔开 
3.元组中的元素值是不允许修改的,但我们可以对元组进行连接组合 
4.函数的返回值一般为一个。而函数返回多个值的时候,是以元组的方式返回的

元祖的操作

tuple1 = ( '1', 'a' , 2.0, 'b', 3 )
#索引操作与列表一致
tuple0 = ()    # 空元组
tuple2 = (20,) # 一个元素,需要在元素后添加逗号


输出结果
('abcd', 786, 2.23, 'runoob', 70.2)

字典

d = {key1 : value1, key2 : value2 }

1.字典是无序的对象集合,列表是有序的对象结合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。 
2.键(key)必须使用不可变类型。 
3.管字典中有多少项,in操作符花费的时间都差不多 

def example(d): 
 for c in d: 
 print(c)

其中:d 是一个字典对象

字典的操作

dict = {}
dict['One'] = 1
dict[2] = 'Two'
dict['Three']=3
dict['Five']=5
dict2={'ONE':1, 'TWO':2, 'THREE': 3}

print(dict)
print(dict2)
del dict['Five']
print(dict)

print(dict['One'])
print(dict.keys())
print(dict.values())
for k,v in dict2.items():
    print(k,":",v)
dict.clear() #清空字典
del dict #删除字典
type(dict2)

dict_pop_key,dcit_pop_value=dict2.popitem()
print('pop-{0}:{1}'.format(dict_pop_key,dcit_pop_value))#随机返回并删除字典中的一对键和值(一般删除末尾对)
for k, v in dict2.items():
    print(k, v,end=";")


dict4={2:'Two',3:'Three',1:'One'}
sorted(dict4.keys())

输出的结果是

{'One': 1, 2: 'Two', 'Three': 3, 'Five': 5}
{'ONE': 1, 'TWO': 2, 'THREE': 3}
{'One': 1, 2: 'Two', 'Three': 3}
1
dict_keys(['One', 2, 'Three'])
dict_values([1, 'Two', 3])
ONE : 1
TWO : 2
THREE : 3
pop-THREE:3
ONE 1;TWO 2;




[1, 2, 3]