python基础学习笔记

在Python中,字典用放在花括号{}中的一系列键—值对表示,如前面的示例所示:

字典:

alien_0 = {'color': 'green', 'points': 5}

创建一个空字典:

alien_0 = {}

增加键值对

alien_0 = {}
alien_0['x_position'] = 0 9 
alien_0['y_position'] = 25

{'y_position': 25, 'x_position': 0}

修改键值对:

alien_0 = {'color': 'green'}

alien_0['color'] = 'yellow'

删除键—值对

alien_0 = {'color': 'green', 'points': 5} 
del alien_0['points'] 

遍历所有的键—值对

user_0 = {
'username': 'efermi', 
'first': 'enrico', 
'last': 'fermi'
}
for key, value in user_0.items(): 
print("\nKey: " + key)
print("Value: " + value)


Key: last 
Value: fermi

Key: first 
Value: enrico

Key: username 
Value: efermi

方法items()

它返回一个键—值对列表。接下来, for循环依次将每个键—值对存储到指定的两个变量中,键—值对的返回顺序也与存储顺序不同

favorite_languages = {
 'jen': 'python',
  'sarah': 'c', 
  'edward': 'ruby', 
  'phil': 'python', 
    }
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " +language.title() + ".")


Jen's favorite language is Python. 
Sarah's favorite language is C. 
Phil's favorite language is Python. 
Edward's favorite language is Ruby.

遍历字典中的所有键 方法keys() values() 只打印键或者值

favorite_languages = {
 'jen': 'python', 
 'sarah': 'c', 'edward': 
 'ruby', 'phil': 
 'python', }

for name in favorite_languages.keys(): 
    print(name.title())

for name in favorite_languages.values(): 
    print(name.title())

sorted()

要以特定的顺序返回元素,一种办法是在for循环中对返回的键进行排序。为此
可使用函数sorted()来获得按特定顺序排列的键列表的副本

favorite_languages = { 
    'jen': 'python',
    'sarah': 'c', 
    'edward': 'ruby', 
    'phil': 'python', 
}
for name in sorted(favorite_languages.keys()): 
    print(name.title() + ", thank you for taking the poll.")

为剔除重复项,可使用集合(set)。 集合类似于列表,但每个元素都必须是独一无二的

favorite_languages = { 
    'jen': 'python', 
    'sarah': 'c', 
    'edward': 'ruby', 
    'phil': 'python', 
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()): 
    print(language.title())

嵌套

有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。你 可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。正如下面的示例将演示的,
嵌套是一项强大的功能

alien_0 = {'color': 'green', 'points': 5} 
alien_1 = {'color': 'yellow', 'points': 10} 
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2] 

for alien in aliens: 
    print(alien)

在字典中存储列表

pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'], 
    }
print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings:")
for topping in pizza['toppings']: 
    print("\t" + topping)



You ordered a thick-crust pizza with the following toppings:
        mushrooms
        extra cheese

字典嵌套列表

favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'], 
'phil': ['python', 'haskell'], 
    }

for name, languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages: 
        print("\t" + language.title())




Jen's favorite languages are:
        Python
        Ruby

Sarah's favorite languages are:
        C

Edward's favorite languages are:
        Ruby
        Go

Phil's favorite languages are:
        Python
        Haskell

字典嵌套字典:

users = { 
    'aeinstein': {
    'first': 'albert', 
    'last': 'einstein', 
    'location': 'princeton', 
    },
    
    'mcurie': {
    'first': 'marie', 
    'last': 'curie', 
    'location': 'paris', },
    }

for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']
    print("\tFull name: " + full_name.title()) 
    print("\tLocation: " + location.title())



Username: aeinstein
        Full name: Albert Einstein
        Location: Princeton

Username: mcurie
        Full name: Marie Curie
        Location: Paris

函数input()

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在 一个变量中,以方便你使用

message = input("Tell me something, and I will repeat it back to you: ") 
print(message)

有时候,提示可能超过一行,例如,你可能需要指出获取特定输入的原因。在这种情况下, 可将提示存储在一个变量中,再将该变量传递给函数input()。这样,即便提示超过一行,input() 语句也非常清晰

prompt = "If you tell us who you are, we can personalize the messages you see." 
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")

使用int()来获取数值输入 使用函数input()时,Python将用户输入解读为字符串

例子:
gaodu = input("ni you duo gao ?")
gaodu = int(gaodu)

if gaodu >= 150:
    print("ke yi jin qu")
else:
    print("bu ke yi jin qu")

%去余,判断偶数或者奇数

shuzi = input("shu ru yi ge shu zi:")
shuzi = int(shuzi)
if shuzi %2 == 0 :
    print("ni shu ru shi de yi ge ou shu")
else :
    print("ni shu ru de shi ji shu")

while循环

a = 1
while a <= 5 :
    print(a)
    a = a + 1

让用户选择何时退出

prompt = "\nTell me something, and I will repeat it back to you:" 
prompt += "\nEnter 'quit' to end the program. "
message = "" 
while message != 'quit':
    message = input(prompt) 
    print(message)

使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于 活动状态。这个变量被称为标志,充当了程序的交通信号灯。你可让程序在标志为True时继续运 行,并在任何事件导致标志的值为False时让程序停止运行。这样,在while语句中就只需检查一 个条件——标志的当前值是否为True,并将所有测试(是否发生了应将标志设置为False的事件) 都放在其他地方,从而让程序变得更为整洁
如 a = True

使用break退出循环

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
    city = input(prompt)
    if city == 'quit': 
        break
    else:
        print("I'd love to go to " + city.title() + "!")

在循环中使用continue

num = 0
while num < 10:
    num = num +1
    if num %2 == 1:
        continue
    print(num)21

在列表之间移动元素

假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移 到另一个已验证用户列表中呢?一种办法是使用一个while循环,在验证用户的同时将其从未验 证用户列表中提取出来,再将其加入到另一个已验证用户列表中

wei_user = ["a" , "b" , "c"]
yanzhengguode = []

while wei_user :
    yanzheng = wei_user.pop()
    print("yan zheng yong hu :" + yanzheng.title())
    yanzhengguode.append(yanzheng)

print("\n yan zheng de suo you yong hu :")
for yanzhengsuoyou in yanzhengguode :
    print(yanzhengsuoyou.title())

结果为:

yan zheng yong hu :C
yan zheng yong hu :B
yan zheng yong hu :A

 yan zheng de suo you yong hu :
C
B
A

删除包含特定值的所有列表元素

假设你有一个宠物列表,其中包含多个值为'cat'的元素。要删除所有这些元素,可不断运 行一个while循环,直到列表中不再包含值'cat'

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] 
print(pets)
while 'cat' in pets: 
    pets.remove('cat')
print(pets)

结果:

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] 
print(pets)
while 'cat' in pets: 
    pets.remove('cat')
print(pets)

使用用户输入来填充字典

可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每 次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答 同被调查者关联起来

a = {}
a_pd = True

while a_pd :
    name = input("\n你叫啥?")
    b = input("你最喜欢谁?")

    a[name] = b
    c = input("谁还接受调查?( yes / no )")

    if c == 'no' :
        a_pd = False

print("----调查结果-----")
for name , a in a.items() :
    print(name + "最喜欢的是:" + a)

结果:

你叫啥?小金
你最喜欢谁?小吴
还有吗?( yes / no )no
----调查结果-----
小金最喜欢的是:小吴
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353