python一些特有语法

[i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
with open("c:list.txt","r",encoding="utf-8") as fr:
    fr=fr.readline()
    print(fr)
卷 本地磁盘 的文件夹 PATH 列表
names=["helo","mike","jordan"]
print(".".join(names))   #python中的字符串相当于不可变序列列表,列表~ join连接的意思
print("hello".join("ABC"))
helo.mike.jordan
AhelloBhelloC
for i ,item in enumerate(names):  //枚举的意思
    print(i,item)
0 helo
1 mike
2 jordan
a=1
b=2
a,b=b,a
print(b,a)
1 2
from collections import deque   #列表优点在于索引很快,需要pop,apend时,deque会使他变成双向列表
names=deque(["mike","lucy","tom"])
names.popleft()
names.appendleft("mark")
print(names)
deque(['mark', 'lucy', 'tom'])
p="A","B",3,"D"
for i in p:
    print(i)

name,gender,sex,addr=p 
print(name,gender,sex,addr)
A
B
3
D
A B 3 D
d={"name":"zhang","sex":1}
for k in d:     
    print(k,d[k])
for k,v in d.items():  #当字典很大会占用大量内存,items()返回一个迭代器对象
    print(k,v)
for k,v in d.iteritems():   #此方法只在Python2中有,可省很多内存,zaiPython3中,等于items()
    print(k,v)
name zhang
sex 1
name zhang
sex 1



---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-36-eee9d47dd0c6> in <module>()
      4 for k,v in d.items():  #当字典很大会占用大量内存,items()返回一个迭代器对象
      5     print(k,v)
----> 6 for k,v in d.iteritems():   #此方法只在Python2中有,可省很多内存
      7     print(k,v)


AttributeError: 'dict' object has no attribute 'iteritems'
text=""
gender="male"
text="男" if gender=="male"else "女"
print(text)

if gender=="male":
    text="男"
else:
    text="女"
print(text)
男
男
if names:
    print("列表不为空")  #判断是否为空,更简洁表示,不需要len()求出长度
if gender:
    print("字符串不为空")
列表不为空
字符串不为空
def fib(n):
    a,b=0,1
    while a<n:
        yield a   #yield生成器用法
        a,b=b,a+b
        return a
print(fib(10))
<generator object fib at 0x0000000004EFCBF8>
if "name"in d:         
    print(d["name"])
else:
    print("没有")         #字典get()方法巧用


d.get("name","unkonwn")     #获取字典中name属性的值,否则print  unknown
zhang





'zhang'
data=[("foo",20),("bark",30),("foo",25),("bark",55)]   #对字典进行分组
groups={}
for key,value in data:
    if key in groups:
        groups[key].append(value)
    else:
        groups[key]=[value]   #将value设定为一个列表,但是从本质上理解,与原先的字符串是同源的,string本就是有序list
print(groups)


groups={}            #更简洁的写法,预设字典默认值
for key,value in data:
    groups.setdefault(key,[]).append(value)
print(groups)
{'foo': [20, 25], 'bark': [30, 55]}
{'foo': [20, 25], 'bark': [30, 55]}
numbers=[1,2,3]       #字典推导式,构建一个字典
my_dic={number:number*2 for number in numbers if number>1 }
print(my_dic)
{2: 4, 3: 6}
posted @ 2017-10-08 15:00  Braveliberty  阅读(181)  评论(0编辑  收藏  举报