一、推导式
普通推导式
list_test
= [i
for i
in range(5)]
list_test
[0, 1, 2, 3, 4]
list_test
= [i
for i
in range(1,11) if i
%2==0]
list_test
[2, 4, 6, 8, 10]
list_test
= [i
for i
in range(11) if i
%2!=0]
list_test
[1, 3, 5, 7, 9]
list_test
= [pow(i
,2) for i
in range(10)]
list_test
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
(2)二维推导式
list_test0
= {j
for i
in range(2,20) for j
in range(i
*i
,20,i
)}
list_test0
{4, 6, 8, 9, 10, 12, 14, 15, 16, 18}
list_test1
= [i
for i
in range(2,20) if i
not in list_test0
]
list_test1
[2, 3, 5, 7, 11, 13, 17, 19]
二、enumerate和format函数
(1)enumerate函数
list_test
= ['I','am','SunYongDi']
for i
,j
in enumerate(list_test
):
print(i
)
print(j
)
0
I
1
am
2
SunYongDi
(2) format函数
str_test0
= '你好{}{}!'.format(',','syd')
str_test0
'你好,syd!'
dict_test
= {'name':'syd','age':'24'}
dict_test1
= '我是{name},今年{age}!'.format(**dict_test
)
dict_test1
'我是syd,今年24!'
list_test
= ['you', 'syd']
list_test1
= 'do {0[0]} like {0[1]}!'.format(list_test
)
list_test1
'do you like syd!'
table_head
= ['id','name','age']
content
= [[1,'R',21],[2,'java',23],[3,'python',25]]
head
= '{0[0]:^8}{0[1]:^8}{0[2]:^8}'.format(table_head
)
print(head
)
for i
in content
:
content_test
= '{0[0]:^8}{0[1]:^8}{0[2]:^8}'.format(i
)
print(content_test
)
id name age
1 R 21
2 java 23
3 python 25
三、文件操作
(1)open函数
a
= ("Fusion recommendation algorithm trust and time weights")
a
.upper
()
'FUSION RECOMMENDATION ALGORITHM TRUST AND TIME WEIGHTS'
with open(r
'E:\1.txt',encoding
="utf-8") as file:
content
= file.read
()
print(content
)
hello 中国
with open(r
'E:\1.txt') as file:
content
= file.read
()
print(content
)
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-90-55d84b025ba7> in <module>
1 with open(r'E:\1.txt') as file:
2 # 读文件
----> 3 content = file.read()
4 print(content)
UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 8: illegal multibyte sequence
with open(r
'E:\1.txt',mode
='r+', encoding
="utf-8") as file:
file.write
("哈哈哈")
content
= file.read
()
print(content
)
中国
四、局部变量与全局变量
(1)局部变量与全局变量
g_test
= 10
def sum():
a0
= 9
g_test
= 10-a0
print(g_test
)
sum()
1
g_test
10
g_test
= 10
def sum():
global g_test
g_test
= 4
print(g_test
)
sum()
4
g_test
4