目录
0、命名方式1、变量的交换(Swapping Variables)2、字符串格式化(String Formatting)3、Yield语法(Yield Statement)4、列表解析式(List Comprehension)5、Enumerate函数(Enumerate Function)6、反向遍历(Looping Backwards)7、字典的合并操作(Dictionary Merging)8、三元运算符(Ternary Operator)9、序列解包(Sequence Unpacking)10、With语句(With Statement)
0、命名方式
定义函数的命名:
def getNovelListUrl():
2、
def getnovelnisturl():
def get_Novel_List_Url():
def get_novel_nist_url():
1、变量的交换(Swapping Variables)
a
= 1
b
= 2
temp
= a
a
= b
b
= temp
a
,b
= b
,a
2、字符串格式化(String Formatting)
name
= "Liming"
print("Hi, I'm " + name
)
name
= "Liming"
country
= "China"
age
= 23
print("Hi, I'm " + name
+ ". I'm from " + country
+ ". And I'm " + str(age
) + ".")
print("Hi, I'm %s. I'm from %s. And I'm %d." %(name
,country
,age
))
print("Hi, I'm {}. I'm from {}. And I'm {}.".format(name
,country
,age
))
print(f
"Hi, I'm {name}. I'm from {country}. And I'm {age}.")
3、Yield语法(Yield Statement)
def fibonacci(n
):
a
= 0
b
= 1
nums
= []
for _
in range(n
):
nums
.append
(a
)
a
,b
= b
,a
+ b
return nums
def fibonacci(n
):
a
= 0
b
= 1
for _
in range(n
):
yield a
a
,b
= b
,a
+ b
for i
in fibonacci
(10):
print(i
)
4、列表解析式(List Comprehension)
fruit
= ["apple","pear","pineapple","orange","banana"]
for i
in range(len(fruit
)):
fruit
[i
] = fruit
[i
].upper
()
print(fruit
)
fruit
= ["apple","pear","pineapple","orange","banana"]
filtered_fruit
= []
for f
in fruit
:
if f
.startswith
("p"):
filtered_fruit
.append
(f
)
print(filtered_fruit
)
5、Enumerate函数(Enumerate Function)
fruit
= ["apple","pear","pineapple","orange","banana"]
for x
in fruit
:
print(x
)
for i
,x
in enumerate(fruit
):
print(i
,x
)
6、反向遍历(Looping Backwards)
fruit
= ["apple","pear","pineapple","orange","banana"]
for i
,x
in enumerate(reversed(fruit
)):
print(i
,x
)
for i
,x
in enumerate(sorted(fruit
)):
print(i
,x
)
7、字典的合并操作(Dictionary Merging)
a
= {"ross": "123456", "xiaoming": "abc123"}
b
= {"liler": "111111", "zhangsan": "12345678"}
c
= {}
for k
in a
:
c
[k
] = a
[k
]
for k
in b
:
c
[k
] = b
[k
]
d
= {**a
, **b
}
print(c
)
print(d
)
8、三元运算符(Ternary Operator)
score
= 50
if score
> 60:
s
= "pass"
else:
s
= "fail"
print(s
)
9、序列解包(Sequence Unpacking)
name
= "San Zhang"
str_list
= name
.split
()
first_name
= str_list
[0]
last_name
= str_list
[1]
print(first_name
,"-------",last_name
)
10、With语句(With Statement)
f
= open("somefile.txt","r")
s
= f
.read
()
f
.close
()
with open("somefile.txt","r") as f
:
s
= f
.read
()
转载请注明原文地址:https://ipadbbs.8miu.com/read-54389.html