码迷,mamicode.com
首页 > 编程语言 > 详细

Python 列表与字典

时间:2021-03-17 14:08:36      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:count   mat   ide   item   not   range   anim   mon   person   

Python 列表与字典

1 列表(Lists)

列表其实就是Python的数组,它支持动态调整大小,并且可以包含不同类型的元素。

a = []
  • 列表的常用方法包括count(key),index(value),reverse(),sort(),append(value),pop()

  • 切片操作:

nums = list(range(5)) 
print(nums) # [0, 1, 2, 3, 4]
print(nums[2:4]) # [2, 3]
print(nums[2:]) # [2, 3, 4]
print(nums[:2]) # [0, 1]
print(nums[:]) # [0, 1, 2, 3, 4]
print(nums[:-1]) # [0, 1, 2, 3]
nums[2:4] = [8, 9]
print(nums) # [0, 1, 8, 9, 4]
  • 列表推导式
nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares) # [0, 4, 16]

1 字典(Map)

Python中的字典类似于C++中的Map。

d = {‘cat‘: ‘cute‘, ‘dog‘: ‘furry‘}  # Create a new dictionary with some data
print(d[‘cat‘])       # Get an entry from a dictionary; prints "cute"
print(‘cat‘ in d)     # Check if a dictionary has a given key; prints "True"
d[‘fish‘] = ‘wet‘     # Set an entry in a dictionary
print(d[‘fish‘])      # Prints "wet"
# print(d[‘monkey‘])  # KeyError: ‘monkey‘ not a key of d
print(d.get(‘monkey‘, ‘N/A‘))  # Get an element with a default; prints "N/A"
print(d.get(‘fish‘, ‘N/A‘))    # Get an element with a default; prints "wet"
del d[‘fish‘]         # Remove an element from a dictionary
print(d.get(‘fish‘, ‘N/A‘)) # "fish" is no longer a key; prints "N/A"

访问字典的方式

d = {‘person‘: 2, ‘cat‘: 4, ‘spider‘: 8}
for animal, legs in d.items():
    print(‘{:s} has {:d} legs‘.format{animal, legs})

Python 列表与字典

标签:count   mat   ide   item   not   range   anim   mon   person   

原文地址:https://www.cnblogs.com/popodynasty/p/14539936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!