python入门(中)

列表

简单数据类型

    

  • 整型<class 'int'>
  • 浮点型<class 'float'>
  • 布尔型<class 'bool'>

  容器数据类型:

 

  • 列表<class 'list'>
  • 元组<class 'tuple'>
  • 字典<class 'dict'>
  • 集合<class 'set'>
  • 字符串<class 'str'>

列表是有序集合,没有固定大小,能够保存任意数量任意类型的python对象

语法:[x1,x2,……,xn]  中括号把所有元素绑在一起,逗号将每个元素分开

1.创建一个普通列表

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x, type(x))
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] <class 'list'>

x = [2, 3, 4, 5, 6, 7]
print(x, type(x))
# [2, 3, 4, 5, 6, 7] <class 'list'>

2.利用range()创建列表

x = list(range(10))
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>

x = list(range(1, 11, 2))
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>

x = list(range(10, 1, -2))
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>

3.利用推导式创建列表

x = [0] * 5
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>

x = [0 for i in range(5)]
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>

x = [i for i in range(10)]
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>

x = [i for i in range(1, 10, 2)]
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>

x = [i for i in range(10, 1, -2)]
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>

x = [i ** 2 for i in range(1, 10)]
print(x, type(x))
# [1, 4, 9, 16, 25, 36, 49, 64, 81] <class 'list'>

x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x, type(x))

# [3, 9, 15, 21, 27, 33, 39,

向列表中添加元素:list.append(obj),只接受一个参数(追加)

        list.extend(seq)在列表末尾一次性追加另一个序列中的多个值(扩展)

插入:list.insert(index, obj)

删除:list.remove(obj)

移除:list.pop([index=- 1]) 默认最后一个,并且返回该元素的值

其他方法:

list.count(obj) 统计某个元素在列表中出现的次数

list.index(x[, start[, end]]) 从列表中找出某个值第一个匹配项的索引位置

list.reverse() 反向列表中元素

list.sort(key=None, reverse=False) 对原列表进行排序。

元组

语法:(x1, x2,……,xn)

创建并访问一个元组

t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python'
print(t1, type(t1))
# (1, 10.31, 'python') <class 'tuple'>

print(t2, type(t2))
# (1, 10.31, 'python') <class 'tuple'>

tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1[1])  # 2
print(tuple1[5:])  # (6, 7, 8)
print(tuple1[:5])  # (1, 2, 3, 4, 5)
tuple2 = tuple1[:]
print(tuple2)  # (1, 2, 3, 4, 5, 6, 7, 8)

元组大小和内容都不可更改,因此只有 count 和 index 两种方法。

  • count('python') 是记录在元组 t 中该元素出现几次,显然是 1 次
  • index(10.31) 是找到该元素在元组 t 的索引,显然是 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值