当前位置:   article > 正文

Python中的列表、元组、字典、集合_[1, 2, 3, ['a', 'b', 'c']]怎么访问

[1, 2, 3, ['a', 'b', 'c']]怎么访问

Python中的列表、元组、字典、集合

1.列表list是可变的对象
2.元组tuple是不可变的对象
3.字典dict类似于Java中的HashMap,以键值对出现
4.集合set类似于列表,区别在于集合不包含重复的值

1.列表list

#!/usr/bin/python
list=[1,2,3,'a','b','c']
print(list[3])  #按索引访问

list[0]="hello" #通过索引更新元素
print(list)

list.append("hi")  #新增单个元素
print(list)

list.insert(1,"world") #在指定位置插入元素
print(list)

list2=[1,3,5,7,9]
list.append(list2) #append只能新增单个元素,会把列表作为一个新的元素添加
print(list)

list.extend(list2) #extend会把列表拆开,然后逐个添加
print(list)

print(list.pop())  #pop()方法默认删除并返回列表最后一个元素

print(list.pop(8)) #pop()方法可删除并返回指定下标的元素

list.remove("hello") #remove()方法可根据元素内容进行删除(删除找到的第一个元素)
print(list)

del list[2] #del关键字可删除指定下标的元素
print(list)

print("world的下标为:",list.index("world")) #通过元素的值查找下标(值不存在会输出错误信息)

list.reverse() #reverse()方法用于反转队列
print(list)

print("a出现的次数为:",list.count("a")) #count()方法用于统计某个元素在列表中出现的次数

number=[9,3,76,54,4,7,32]
number.sort() #sort()方法用于对列表元素进行排序
print(number)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
运行结果如下:
a
['hello', 2, 3, 'a', 'b', 'c']
[
  • 1
  • 2
  • 3
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号