拆包(元组中)
co=(1,2,3) x,y,z=co print(x)
自动将1分配给x,以此类推
字典
customer = { "name":"John Smith", "age":30, "is_verified":True }//定义方法,前面的是关键字,必须唯一 print(customer["name"]) //访问 customer["name"]="Jack Smith" //可更改 print(customer.get("name")) //另一种访问方法 print(customer.get("birthday")) //若用get方法访问不存在的关键字,将返回None,用第一种访问方法将报错 print(customer.get("birthday"),"2008")
//可赋值不存在的关键字
执行:
John Smith
Jack Smith
None
None 2008
进程已结束,退出代码为 0
字典练习:翻译
用户输入电话号码,翻译为英文单词并输出
phone=input("phone:") dict={ "1":"one", "2":"two", "3":"three", "4":"four" } output="" for i in phone: output+=dict.get(i,"!")+" "//注意,“”里带空格,以便输出时可以分开 print(output)
执行示例:
phone:1234
one two three four
进程已结束,退出代码为 0
一个有趣的小示例:
用户输入happy或者sad,替换成表情符,输出
message = input(">") words=message.split(' ') print(words)//这两行将输入的词以空格为边界分开,形成列表,可以查看 emojis={ "happy":":)", "sad":":(" } output="" for i in words: output+=emojis.get(i,i)+" " print(output)
执行结果:
>i am happy
['i', 'am', 'happy']
i am :)
进程已结束,退出代码为 0
>i am so sad
['i', 'am', 'so', 'sad']
i am so :(
进程已结束,退出代码为 0