[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))
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
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():
print(k,v)
for k,v in d.iteritems():
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("列表不为空")
if gender:
print("字符串不为空")
列表不为空
字符串不为空
def fib(n):
a,b=0,1
while a<n:
yield a
a,b=b,a+b
return a
print(fib(10))
<generator object fib at 0x0000000004EFCBF8>
if "name"in d:
print(d["name"])
else:
print("没有")
d.get("name","unkonwn")
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]
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}