美文网首页
第三章 列表简介

第三章 列表简介

作者: 仙境源地 | 来源:发表于2019-11-26 17:59 被阅读0次

3.1列表是什么

使用方括号([])来标识列表

# encoding=utf-8
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']

3.2访问,修改,添加,删除列表元素

看代码总是最直接的

# encoding=utf-8
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0] + "," + bicycles[1])
# 访问最后一个元素[-1],索引-2访问倒数第二个元素 java没有
print(bicycles[-1] + "," + bicycles[-2])
# IndexError: list index out of range
# print(bicycles[-5])
# print(bicycles[4])

bicycles[0] = 'car'
print(bicycles)

ages = []
print(ages)
# 列表尾部添加
ages.append(10)
ages.append(30)
ages.append(45)
print(ages)
# 指定位置添加
ages.insert(0, 1)
print(ages)
# 删除指定位置元素
del ages[-1]
del ages[0]
print(ages)
# 从队尾弹出元素
age = ages.pop()
print(ages.__str__() + "," + str(age))

ages.append(50)
ages.append(60)
ages.append(70)
# 从指定位置弹出元素
age = ages.pop(-2)
print(ages.__str__() + "," + str(age))


age_10 = 10
ages.append(age_10)
# 删除指定值,只会删除第一个满足条件的值,如果没有找到则会抛错
ages.remove(age_10)
print(ages)
# ValueError: list.remove(x): x not in list
# ages.remove(100000)
['trek', 'cannondale', 'redline', 'specialized']
trek,cannondale
specialized,redline
['car', 'cannondale', 'redline', 'specialized']
[]
[10, 30, 45]
[1, 10, 30, 45]
[10, 30]
[10],30
[10, 50, 70],60
[50, 70, 10]

3.3 组织列表

列表函数:sort(),
通用函数:sorted(),len()

# encoding=utf-8
# sort列表排序
names = ['zhang', 'wang', 'shi', 'chu']
names.sort()
print(names)
# sort列表逆向排序
names.sort(reverse=True)
print(names)
# sorted()函数返回排好序的列表,但不改变原始列表顺序
asc_names = sorted(names)
print(str(names) + "," + str(asc_names))
desc_names = sorted(names, reverse=True)
print(str(names)+","+str(desc_names))

# 反转列表元素
names.append('tian')
names.reverse()
print(names)

# 查询列表长度
print(len(names))
print(names.__len__())
['chu', 'shi', 'wang', 'zhang']
['zhang', 'wang', 'shi', 'chu']
['zhang', 'wang', 'shi', 'chu'],['chu', 'shi', 'wang', 'zhang']
['zhang', 'wang', 'shi', 'chu'],['zhang', 'wang', 'shi', 'chu']
['tian', 'chu', 'shi', 'wang', 'zhang']
5
5

相关文章

  • python编程(从入门到实践)3章

    第三章 列表简介 列表是什么 在python中,用方括号([ ])表示列表,并用逗号分割其中的元素。下面是一个简单...

  • Python编程:从入门到实践 Day3

    第三章:列表简介 1.列表的定义和命名 (1)定义 用方括号定义一个列表:[ ]用逗号分隔其中的元素:, (2)命...

  • Python入门学习笔记-2

    第三章 列表简介 输出末尾元素 python用 -1 来引索末尾元素 var = (“一” , ”二” , ”三”...

  • 第三章:列表简介

    列表(list)由一系列按特定顺序排列的元素(item)组成 给列表指定表示复数的名称,易于区分 创建列表: 使用...

  • 第三章 列表简介

    3.1列表是什么 使用方括号([])来标识列表 3.2访问,修改,添加,删除列表元素 看代码总是最直接的 3.3 ...

  • Head First html和css(3)

    第三章 列表 可以在列表中嵌套列表,当然,需要夹在li之中。

  • python编程 | 第三章 列表简介

    python编程系统学习指路:快速学习 | python编程:从入门到实践 | Windows 1 列表是什么 列...

  • html+css 3

    开篇第三章 一、网页上有很多信息的列表,如新闻列表、图片列...

  • 无标题文章

    简介 文章列表

  • Python:列表简介

    概念 列表由一系列按特定顺序排列的元素组成,可以将任何元素加入列表中。Python中用[]来表示列表,用逗号分隔元...

网友评论

      本文标题:第三章 列表简介

      本文链接:https://www.haomeiwen.com/subject/udsywctx.html