Python入门3-变量2

2020-01-06 11:06:09 浏览数 (1)

1.字典(使用花括号定义)

dairy_section = {}

dairy_section["breakfast"] = ("break","milk")

dairy_section["lunch"] = ("noodles","rices","dishes")

dairy_section["dinner"] = ("porridge","steamed bun")

读取时可以使用:

1)print(dairy_section):显示全部的值

2)dairy_section.get("breakfast"):读取特定值

3)从字典中取键

print_keys = dairy_section.keys()

print_values = dairy_section.values()

2.引用序列的最后一个元素(元组和列表均属于序列)

元组(列表)名称[-1],依次类推,比如week = ("Sunday","monday","Tuesday")

可使用print(week[-1])打印出"Tuesday"

3.将序列分片

1)将元组分片:例如workday = ("Monday","Tuesday","Wednesday","Thursday","Friday")

print(workday[0:2]),显示"Monday",“Tuesday”

2)将列表分片:例如workday = ["Mondy","Tuesday","Wednesday","Thursday","Friday"]

print(workday[1:3]),显示"Tuesday","Wednesday"

3)将字符分片:例如workday = "from Monday to friday"

print(workday[2:5]),显示"om "

4.从列表中弹出元素

today_times = [2,5,3,6]

A = today_times.pop(0)

print(A),显示2,且print(today_times)时显示[5,3,6]

5.计算元组、列表或字典的长度

len(元组名或列表名或字典名)

6.处理集合

alphabet = ['a','b','b','c','d','e','e']

alph2 = set(alphabet)

print(alph2)显示{'a','b','c','d','e'}

0 人点赞