Python之操作列表

    科技2026-02-07  2

    操作列表

    1.遍历整个列表2.创建数值列表rang()函数 3.使用列表的一部分切片并遍历切片复制链表 4.元组关于代码格式 总结

    1.遍历整个列表

    for 循环执行缩进的语句,没有缩进的语句代码只执行一次,不会重复执行。

    // manguages = ['alice','david','carolina'] for manguage in manguages: print("manguage.title()" + ", that was a great trick!") print("I can not wait to see your next trick," + "manguage.title()" + ".\n") print("Thank you everyone. That was a great magic show!")

    应用:可以用for循环来初始化游戏—遍历角色列表,并将每个角色打印到屏幕上。再在循环后面添加一个不缩进的代码块,在屏幕上绘制所有角色后先显示一个Play Now按钮。

    2.创建数值列表

    rang()函数

    打印2-10中的偶数,代码如下

    //even_numbers = list(range(2,11,2)) print (even_number) //[2,4,6,8,10]

    将1-10的整数的平方加入到列表中,代码如下

    //squares = [] for value in range(1,11): square = value**2 squares.append(square) print squares //[1,4,9,16,25,36,49,64,81,100]

    更简洁的代码如下

    //squares = [] for value in range(111): squares.append(value**2) print squares //[1,4,9,16,25,36,49,64,81,100]

    列表解析将使代码更加简洁,同时要注意for语句末尾没有冒号

    //squares = [value**2 for value in range(1,11)] print(squares)

    对数字进行简单的统计计算

    //digits = [1,2,3,4,5,6,7,8,9,0] min(digits) max(digits) sum(digits)

    3.使用列表的一部分

    切片并遍历切片

    //players = ['charles', 'martina', 'michael', 'florence', 'eli'] print("Here are my first three players on my team:") for player in players[:3]: print(player.title())

    [:]表示遍历链表 索引从头到尾 [:4]表示遍历链表 索引从0到3 [1:]表示遍历链表 索引从1到结尾

    复制链表

    使用语句 list_two = list_one[:]

    //my_foods = ['pizza','falafel','carrot cake'] friend_foods = my_foods[:] my_foods.append('rice') my_foods.append('ice cream') print("My favorite foods are") print("my_foods") print("\nMy friend's favorite foods are") print("friend_foods")

    不能简单的将friend_foods = my_food,否则就得不到两个列表。

    4.元组

    元组用圆括号(),列表用方括号[],列表的元素可改,但元组的元素不可改。若想修改元组内的元素,则

    //dimensions = (10,200) for dimension in dimensions: print (dimension) dimensions = (10,400) for dimension in dimensions: print (dimension) //10 200 10 400

    如果要存储的数字在程序的整个周期内都不可变,则还用元组来定义。

    关于代码格式

    PEP 8建议每级缩进都是用4个空格。也可使用制表符,但注意不要混合使用空格和制表符。 关于行长,每行不建议超过80字符,注释的长度不超过72字符。

    总结

    1.遍历列表 for name in range[0:3] 2.列表解析使代码更简洁 squares = (value**2 for value in range[:]) 3.对列表切片并遍历 for name in names[1:3]: 4.复制列表 for name in names[:] 5.元组的遍历和修改 元组用圆括号() eg names = (‘shengnan’,‘nasong’)

    Processed: 0.010, SQL: 9