程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(1)

Python第四章

发布于2019-08-06 11:10     阅读(994)     评论(0)     点赞(4)     收藏(3)


Python第四章总结
  写第三章总结的时候,由于已经看过一遍了,所以写的时候需要重新再看一遍,但是由于看过了一遍,所以看的就不仔细,所以总结的也没有那么好,从这一章往后,我打算看一点写一点。第四章是接着第三章,讲解列表的,主要是如何遍历列表。
  4.1 遍历整个列表
  遍历整个列表中的元素,使用的是for循环:
  magicians=[‘alice’,‘david’,‘carolina’]
  for magician in magicians:
  print(magician)
  {一定要注意冒号,for循环后面的冒号}

  在for循环后面,缩进的都是循环语句的一部分,没有缩进的语句只执行一次。所以,在写程序的时候一定要记得哪些语句需要缩进,哪些不需要缩进。
  4.3 创建数值列表
  1、函数range()

  for number in range(1,5):
  print(number){注意:差一打印}

  2、使用 range()创建数字列表
  要创建数字列表,可使用函数list()将range()的结果直接转换为列表。
  numbers = list(range(1,6))
  print(numbers)

  result:[1, 2, 3, 4, 5]
  使用函数range()时,还可指定步长
  even_numbers = list(range(2,11,2))
  print(even_numbers)
  {函数range()从2开始数,然后不断地加2,直到达到或超过终值(11)}

  result:[2, 4, 6, 8, 10]
  对数字列表执行简单的统计计算:
  digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
  min(digits)
  max(digits)
  sum(digits)
  列表解析:
  squares=[value**2 for value in range(1,11)]
  print(squares)

  列表切片,访问列表的部分元素:
  players=[‘charles’,‘martina’,‘michael’,‘florence’,‘eli’]
  print(players[0:3]):访问列表的前三个元素
  print(players[1:4]):访问列表的234号元素
  print(players[:3]):访问前三个元素
  print(players[2:]):访问从第三个元素到列表最后的所有元素
  print(players[-3:]):访问列表的倒数三个元素

  result:
  [‘charles’, ‘martina’, ‘michael’]
  [‘martina’, ‘michael’, ‘florence’]
  [‘charles’, ‘martina’, ‘michael’]
  [‘michael’, ‘florence’, ‘eli’]
  [‘michael’, ‘florence’, ‘eli’]

  遍历切片元素:
  for player in players[:3]
  复制列表
  {要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引( [:])。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。}:

  my_foods=[‘pizza’,‘falafel’,‘carrot cake’]
  friend_foods=my_foods[:]

  my_foods.append(‘cannoli’)
  friend_foods.append(‘ice cream’)
  print(“My favorite foods are:”)
  print(my_foods)
  print("\nMy friend’s favorite foods are:")
  print(friend_foods)
  result:
  My favorite foods are:
  ‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]
  
  My friend’s favorite foods are:
  [‘pizza’, ‘falafel’, ‘carrot cake’, ‘ice cream’]
 4.5 元组
 元素不改变的列表称为元组。
  第四章的内容大概就是这样吧,最近会莫名其妙的不开心,不知道为什么。最近特别喜欢听一首歌《像我这样的人》。和在一起舒服的人在一起真的是一件超幸福的事。



所属网站分类: 技术文章 > 博客

作者:放羊人

链接:https://www.pythonheidong.com/blog/article/8184/72b76e883a81a36a5122/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)