当前位置: 首页 > news >正文

Python 入门教程 8 ---- Python Lists and Dictionaries


第一节

1 介绍了Python的列表list

2 列表的格式list_name = [item1 , item2],Python的列表和C语言的数组很像

3 列表可以为空,就是empty_list = [],比如数组为空

4 举例

zoo_animals = ["pangolin", "cassowary", "sloth", "dog"];
# One animal is missing!

if len(zoo_animals) > 3:
	print "The first animal at the zoo is the " + zoo_animals[0]
	print "The second animal at the zoo is the " + zoo_animals[1]
	print "The third animal at the zoo is the " + zoo_animals[2]
	print "The fourth animal at the zoo is the " + zoo_animals[3]

第二节

1 介绍了我们可以使用下标来访问list的元素,就像数组一样

2 下标从0开始,比如list_name[0]是第一个元素

3 练习:输出列表numbers的第二个和第四个数的和

numbers = [5, 6, 7, 8]

print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
# Your code here!
print numbers[1] + numbers[3]


第三节

1 介绍了我们可以使用下标来对第几个元素进行赋值

2 比如lisy_name[2] = 2,就是把列表的第三个值赋值为2

3 练习:把列表zoo_animals中的tiger换成其它的动物

zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked 
#the poor tiger and ate it whole.

# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"

# What shall fill the void left by our dear departed tiger?
# Your code here!
zoo_animals[3] = "dog"


第四节

1 介绍了list中添加一个item的方法append()

2 比list_name.append(item),求列表list_name中有几项就是利用len(list_name)

3 练习:在列表suitcase在增加三项,然后求出它的元素的个数

suitcase = [] 
suitcase.append("sunglasses")

# Your code here!
suitcase.append("a")
suitcase.append("b")
suitcase.append("c")

# Set this to the length of suitcase
list_length = len(suitcase)

print "There are %d items in the suitcase." % (list_length)
print suitcase


第五节

1 介绍了list列表怎样得到子列表list_name[a:b],将得到下标a开始到下标b之前的位置

2 比如列表my_list = [1,2,3,4],那么my_list[1:3]得到的将是[2,3]


my_list = [0, 1, 2, 3]
my_slice = my_list[1:3]
print my_list
# Prints [0, 1, 2, 3]
print my_slice
# Prints [1, 2]

3 如果我们默认第二个值,那么将会直接到末尾那个位置。如果默认第一个值,值是从头开始

my_list[:2]
# Grabs the first two items
my_list[3:]
# Grabs the fourth through last

4 练习:把first列表设置为suitcase的前两项,把middle列表设置为suitcase的中间两项,把last列表设置为suitcase的后两项

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

# The first two items
first = suitcase[0:2] 
# Third and fourth items
middle = suitcase[2:4]
# The last two items
last = suitcase[4:]


第六节

1 介绍了不仅列表可以得到子串,字符串也满足

2 比如string[a:b]是得到从下标a开始到b之前的子串

3 练习:把三个变量分别设置为对应的子串

animals = "catdogfrog"
# The first three characters of animals
cat = animals[:3]   
# The fourth through sixth characters
dog = animals[3:6]   
# From the seventh character to the end
frog = animals[6:] 


第七节

1 介绍了列表的两种方法index(item)和insert(index , item)

2 index(item)方法是查找item在列表中的下标,使用方法list_name.index(item)

3 insert(index,item)是在下标index处插入一个item,其余的后移,使用方法list_name.insert(index , item)

4 练习:使用index()函数找到列表中的"duck",然后在当前位置插入"cobra"

如果我们使用print list_name,就是直接输出列表的所有元素

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
# Use index() to find "duck"
duck_index = animals.index("duck")

# Your code here!
animals.insert(duck_index,"cobra")

# Observe what prints after the insert operation
print animals 

第九节

1 介绍我们可以使用for循环来遍历列表的每一个元素

2 比如for variable in list_name:

statement

这样我们可以枚举列表的每一个元素

3 练习:打印列表的每一个元素的值*2

my_list = [1,9,3,8,5,7]

for number in my_list:
    # Your code here
    print 2*number


第十节

1 介绍了列表的另外一种方法sort(),可以对列表进行排序,默认是从小到打排序

2 使用的方法是list_name.sort()

3 列表中删除一个item的方法list_name.remove(item)

beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")
print beatles
>> ["john","paul","george","ringo"]

4 练习:利用for循环把没一项的值的平方加入列表square_list,然后对square_list排序输出

start_list = [5, 3, 1, 2, 4]
square_list = []

# Your code here!
for numbers in start_list:
    square_list.append(numbers**2)
print square_list.sort()


第十一节

1 介绍了Python中的字典,字典的每一个item是一个键值对即key:value

2 比如字典d = {'key1' : 1, 'key2' : 2, 'key3' : 3},有三个元素

3 Python的字典和C++里面的map很像,我们可以使用d["key1"]来输出key1对应的value

4 练习:打印出'Sloth'和'Burmese Python'对应的value

注意在脚本语言里面可以使用单引号也可以使用双引号来表示字符串

# Assigning a dictionary with three key-value pairs to residents:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

# Prints Puffin's room number
print residents['Puffin'] 

# Your code here!
print residents['Sloth']
print residents['Burmese Python']


第十二节

1 介绍了三点

1 字典和列表一样可以是空的,比如d = {}就是一个空的字典

2 字典里面添加一个键值对或者是改变已有key的value,使用这种方法 dict_name[key] = value
3 我们也可以使用len(dict_name)求出字典的元素的个数

2 练习:至少添加3个键值对到字典menu中

# Empty dictionary
menu = {} 

# Adding new key-value pair
menu['Chicken Alfredo'] = 14.50 
print menu['Chicken Alfredo']

# Your code here: Add some dish-price pairs to menu!
menu["a"] = 1
menu["b"] = 2
menu["c"] = 3

# print you code
print "There are " + str(len(menu)) + " items on the menu."
print menu


第十三节

1 介绍了我们可以删除字典中的键值对

2 我们使用del dict_name[key],这样将删除键值为key的键值对

3 练习:删除key为"Sloth"和"Bengal Tiger",并且设置key为"Rockhopper Penguin"的val和之前的不一样

# key - animal_name : value - location 
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}

# A dictionary (or list) declaration may break across multiple lines
# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']

# Your code here!
del zoo_animals["Sloth"]
del zoo_animals["Bengal Tiger"]
zoo_animals["Rockhopper Penguin"] = "aa"

# print you code
print zoo_animals


第十四节

1 介绍了字典中一个key可以对应不止一个的value

2 比如my_dict = {"hello":["h","e","l","l","o"]},那么key为"hello"对应的value有5个,我们可以使用my_dict["hello"][index]来取得下标为index的value,比如index为1的时候是"e"

3 对于一个key对应多个value的话,我们应该要用list来保存这些value

4对于一个key对应多个value的话,我们还可以对这个key的val进行排序,比如my_dict["hello"].sort()

4 练习

1 在字典inventory中添加一个key为'pocket',值设置为列表["seashell" , "strange berry" , "lint"]

2 对key'pocket'的value进行排序

3 删除字典inventory中key为'backpack'的键值对

4 把字典inventory中key为'gold'的value加一个50

# Assigned a new list to 'pouch' key
inventory = {'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], 
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort() 
# Here the dictionary access expression takes the place of a list name 

# Your code here
inventory['pocket'] = ["seashell" , "strange berry" , "lint"]
inventory['pocket'].sort()
del inventory['backpack']
inventory['gold'] = [500 , 50]




相关文章:

  • linux上安装RAC时不使用asmlib的多路径配置
  • HDOJ, 杭电1219, ACme简单字符串题
  • Java RandomAccessFile
  • Sass的准备工作有哪些
  • oracle RAC 10g 升级到11g (out of place) 回退方案
  • 个人站长的生存空间是否越来越小?
  • 弥补两个不足来提升企业站流量
  • 中国象棋程序的设计与实现(高级版)(2012本科毕业论文等重要文档资料)
  • linux arping命令学习
  • linux的多任务编程-线程池
  • 裸设备上的oracle文件备份-----HP-UX下oracle的裸设备大小
  • Oracle 11.2.0.2.0 RAC环境一次内存溢出ORA-04031问题的处理
  • 软件设计之道_读书纪要
  • enq: TX - row lock contention“等待事件的处理
  • 大众点评笔试算法之质因数分解
  • 【个人向】《HTTP图解》阅后小结
  • github从入门到放弃(1)
  • Java编程基础24——递归练习
  • Java的Interrupt与线程中断
  • Node.js 新计划:使用 V8 snapshot 将启动速度提升 8 倍
  • SQLServer之索引简介
  • vue-router的history模式发布配置
  • 算法之不定期更新(一)(2018-04-12)
  • 听说你叫Java(二)–Servlet请求
  • MPAndroidChart 教程:Y轴 YAxis
  • 基于django的视频点播网站开发-step3-注册登录功能 ...
  • ​比特币大跌的 2 个原因
  • ​力扣解法汇总1802. 有界数组中指定下标处的最大值
  • # C++之functional库用法整理
  • #LLM入门|Prompt#3.3_存储_Memory
  • $.type 怎么精确判断对象类型的 --(源码学习2)
  • ()、[]、{}、(())、[[]]命令替换
  • (BFS)hdoj2377-Bus Pass
  • (LNMP) How To Install Linux, nginx, MySQL, PHP
  • (ZT)薛涌:谈贫说富
  • (分类)KNN算法- 参数调优
  • (力扣题库)跳跃游戏II(c++)
  • (三)uboot源码分析
  • (四)linux文件内容查看
  • (译)计算距离、方位和更多经纬度之间的点
  • (原創) 博客園正式支援VHDL語法著色功能 (SOC) (VHDL)
  • (转)jQuery 基础
  • (转)Linux整合apache和tomcat构建Web服务器
  • (转)原始图像数据和PDF中的图像数据
  • (轉貼)《OOD启思录》:61条面向对象设计的经验原则 (OO)
  • ****Linux下Mysql的安装和配置
  • ***linux下安装xampp,XAMPP目录结构(阿里云安装xampp)
  • ***原理与防范
  • .bat批处理(八):各种形式的变量%0、%i、%%i、var、%var%、!var!的含义和区别
  • .Net 8.0 新的变化
  • .Net Remoting(分离服务程序实现) - Part.3
  • .net 反编译_.net反编译的相关问题
  • .NET 命令行参数包含应用程序路径吗?
  • .NetCore项目nginx发布
  • .net之微信企业号开发(一) 所使用的环境与工具以及准备工作