if __name__ == __main__
python 没有统一入口,__name__
:是内置变量,可用于表示当前模块的名字。如果一个 .py 文件(模块)被直接运行时,其__name__
值为__main__
,即模块名为__main__
。
PI = 3.14
def main():
print("PI:", PI)
if __name__ == "__main__": # __name__ = __main__
main()
1、怎么查出通过 from xx import xx导⼊的可以直接调⽤的⽅法?
help函数
2、了解Collection模块,编写程序以查询给定列表中最常见的元素。
题目说明:
输入:language = [‘PHP’, ‘PHP’, ‘Python’, ‘PHP’, ‘Python’, ‘JS’, ‘Python’, ‘Python’,‘PHP’, ‘Python’]
输出:Python
from collections import Counter
def most_element(language):
""" Return a list of lines after inserting a word in a specific line. """
cnt = Counter()
for w in language:
cnt[w] += 1
cnt = sorted(cnt.items(), key=lambda x: x[1], reverse=True)
return cnt[0][0]
1、假设你获取了用户输入的日期和时间如2020-1-21 9:01:30
,以及一个时区信息如UTC+5:00
,均是str
,请编写一个函数将其转换为timestamp:
题目说明:
import datetime
import re
from dateutil import parser
dt_str='2020-6-1 08:10:30'
tz_str='UTC+7:00'
def to_timestamp(dt_str, tz_str):
dt = parser.parse(dt_str)
tz_r = re.match(r'^UTC([+|-]\d{1,2}):00$', tz_str) # UTC中获取时区信息
tz = datetime.timezone(datetime.timedelta(hours=int(tz_r.group(1)))) # 创建时区UTC
dt = dt.replace(tzinfo=tz) # 利用tzinfo属性将datetime强制设置成指定时区
return dt.timestamp() # 返回timestamp
2、编写Python程序以选择指定年份的所有星期日。
题目说明:
from datetime import date, timedelta
def allsundays(year):
d = date(year, 1, 1) # January 1st
d += timedelta(days = 6 - d.weekday()) # First Sunday
while d.year == year:
yield d
d += timedelta(days = 7)
for d in allsundays(2020):
print(d)