Python的 100道题目

本应该是100道,因不可抗力变成97道

#-*- coding:utf-8 -*-

#1. 计算2的3次⽅
# a = input("请输入底数:")
# b = input("请输入指数:")
# def mi(a,b):
#
#     c = a**b
#     print c
#
# # mi(a,b)
# # x = input("请输入底数:")
# # n = input("请输入指数:")
#
# def power(x,n):
#     s =1
#     while n > 0:
#         n = n -1
#         s = s * x
#     return s
# p = power(2,8)
# print p

print (pow(2,5))

# 2. 找出序列中的最⼤最⼩值
li = [12,56,2,88,68,26,14,799]
a = max(li)
b = min(li)
print a, b

# 3.将字符列表转为字符串
# l = [12,56,2,88,68,26,14,799]
# print(str(l))
# print(type(str(l)))

# join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串
strList = ["zhangweijian","is ","a","good  Boy"]
st = " ".join(strList)
print st

# 4. 快速打印出包含所有 ASCII 字⺟(⼤写和⼩写)的字符串
import string
print string.ascii_letters

# 5.让字符串居中
# 字符串中的 center ⽅法,他会在两边⾃动填充字符(默认为空格),让字符串居zhong
cen = "zhangweijian"
print(cen.center(20))
print(cen.center(30,'*'))

# 6.在字符串中找到⼦串
# find ⽅法,如果找到,就返回⼦串的第⼀个字符的索引,否则返回 -1
str1 = "zhang wei jian is a good boy"
print(str1.find("jian"))
print(str1.find("n"))
print(str1.find("a"))
print(str1.find("ian"))
print(str1.find("ang"))

# 7. 让字符的⾸字⺟⼤写,其他字⺟⼩写
# title ⽅法
str2 = "zhang"
print(str2.title())

# ⽤ string 模块⾥的 capwords ⽅法
print(string.capwords(str2))

# 8.清空列表内容

#⽤ clear ⽅法
list1 = {12,56,2,88,68,26,14,799}       #//集合
print(list1.clear())

# ⽤切⽚赋值的⽅法
list2 = [12,56,2,88,68,26,14,799]
list2[:] = []
print list2

# 9.计算指定的元素在列表中出现了多少次
#count ⽅法
list3 = [12,56,2,88,68,26,14,799,2,56,2,89,14,2,2]
print(list3.count(2))


# 10.在列表末尾加⼊其它元素
list4 = [12,56,2,88,68,26,14,799,2,56,2,89,14,2,2]
list5 = [33,44,55]
lis = list4.extend(list5)
print(list4)
print(list4.append( "zhang"))
print list4

#extend 和列表相加的区别
# extend 是直接在 list4 列表⾥加⼊元素,相加会⽣成⼀个新元素,并不会对 list4 做修改
list6 = [100,200,300]
lis2 = list4 + list6
print lis2
print list4

# 11.查找列表中某个元素第⼀次出现的索引,从0 开始
list7 = [12,56,2,88,68,26,14,799,2,56,2,89,14,2,2]
print(list7.index(26))

# 12.将⼀个对象插⼊到列表中
list8 = [12,56,2,88,68,26,14,799,2,56,2,89,14,2,2]
list8.append(9999)
print list8
list8.insert(4,1777)
print list8

# 用切片的方式
list8[2:3] = [666]      # 占掉了index 为2 的值
print(list8)
list8[2:2] = [777]
print(list8)

# 13.删除列表中元素

# 删除指定元素   remove ⽅法只会删除第⼀次出现的元素
list8.remove(12)
print(list8)

# pop ⽅法可以删除指定元素,不指定位置的话默认删除最后⼀个元素
print(list8.pop())
print(list8.pop(2))
print(list8)

# 14.让列表按相反顺序排列
list8.reverse()
print list8

# 用切片方式
print list8

print list8[::-1]

# 15.表示只包含⼀个元素的元组
tu = (5,)
print(type(tu))

# 16.批量替换字符串中的元素
str3 = 'zhang wei jian'

print(str3.replace('a','mm'))

print (str3.replace('a','jj',1))

# 17.把字符串按照空格进⾏拆分
# ⽤ split ⽅法,括号为空的情况下默认以空格拆分
print(str3.split(' '))
print(str3.split())

# 18.去除字符串⾸位的空格
str4 = ' zhang wei jian '
print str4
print (str4.strip())

# 19. 给字典中不存在的key指定 默认值
dict1 = {1 :'a', 2 :'b', 3 :'c'}
print(dict1.get(2,'bb'))
print(dict1.get(4,'mm'))

# 20.快速求 1 到 100 所有整数相加之和
print(sum(range(1,101)))

# 21.查出模块包含哪些属性
#dir ⽅法
dir()
import requests
dir(requests)

# 22.快速查看某个模块的帮助⽂档
range.__doc__

# 23.快速启动浏览器打开指定⽹站
# ⽤ webbrowser 库
import webbrowser
webbrowser.open('http://www.python.org')

# 24.Python⾥占位符怎么表示?
pass
#⽤ pass 占位,当你还没想好代码块的逻辑时,你需要运⾏代码调试其他功能,需要加占位符,不然会报错

# 25.给函数编写⽂档
# 在 def 语句后⾯把注释⽂档放在引号(单引、双引、三引都可以)⾥⾯就⾏,这个⽂档可以通过 function.__doc__访问
def square(x):
    '''返回平方值'''
    return x*x

square.__doc__

# 26.定义私有⽅法
## 在⽅式名称前加两个下斜杠 __
class Person:
    def __name(self):
        print('私有⽅法')
#### ⽤ from module import * 导⼊时不会导⼊私有⽅法

# 27.判断⼀个类是否是另⼀个类的⼦类
## ⽤ issubclass ⽅法,2 个参数,如果第⼀个参数是第⼆个参数的⼦类,返回 True,否则返回 False

class A:
 pass
class B(A):
 pass
issubclass(B, A)  # True

# 28.从⼀个⾮空序列中随机选择⼀个元素
## ⽤ random 中的 choice ⽅法
import random
print(random.choice(list8))
print(random.choice(['uu',34,'aa',55,78,'dd','bb']))

# 29.查出通过 from xx import xx导⼊的可以直接调⽤的⽅法
##  all ⽅法,这个⽅法查出的是模块下不带_的所有⽅法,可以直接调⽤
print(random.__all__)

# 30.花括号{} 是集合还是字典?
## 字典
type({})  #  <class 'dict'>

# 31. 求两个集合的并集
## 1.解法1:⽤ union ⽅法
dict2 = {6,7,8,9}
dict3 = {8,9,1,2}
print(dict2.union(dict3))     # set([1, 2, 6, 7, 8, 9])

## 2.解法2:使⽤按位或运算符 |
print(dict2 | dict3)

# 32.求两个集合的交集
## 1. 解法一
print(dict2 & dict3)
## 2.解法2:⽤ intersection ⽅法
print(dict2.intersection(dict3))

# 33.求两个集合中不重复的元素
#差集指的是两个集合交集外的部分
## 1.使⽤运算符 ^
print(dict2 ^ dict3)

## 2.解法2:使⽤ symmetric_difference ⽅法
print(dict2.symmetric_difference(dict3))

# 34.求两个集合的差集
## 解法1:⽤运算符 -
print(dict2 - dict3)
print(dict3 - dict2)

## 解法2:⽤ difference ⽅法
print(dict2.difference(dict3))

# 35. 从⼀个序列中随机返回 n 个不同值的元素
## ⽤ random 中的 sample ⽅法
print(random.sample(list8, 3))

# 36.⽣成两个数之间的随机实数
## ⽤ random 中的 uniform ⽅法
print(random.uniform(10,100))

# 37.在等差数列中随机选择⼀个数
## ⽤ random 中的 randrange ⽅法
print(random.randrange(0,100,5))

# 38. 在⽂件⾥写⼊字符
## ⽤ open 函数,模式⽤ w
with open('bruce.txt', 'w') as f:
    f.write('hello world')

# 39.读取⽂件内容
## ⽤ open 函数,模式⽤ r(默认情况下是 r)
with open('bruce.txt', 'r') as f:
    f.read()

## 'hello world'

# 40.把程序打包成 exe ⽂件
## 安装py2app

'''
pip3 install py2app
cd 到Demo.py⽂件所在的⽬录
py2applet --make-setup Demo.py 完成显示⽣成setup.py
'''

# 41.获取路径下所有⽬录名称
## ⽤ sys 下的 path ⽅法,返回的是⽬录名称的字符串列表
import sys
sys.path

# 42.Python 环境下怎么执⾏操作系统命令
## ⽤ os 模块下的 system ⽅法
import os
#  os.system('cd /Users/brucepk/Desktop && mkdir aaa.txt')


# 43.么将当前时间转为字符串
## ⽤ time 模块⾥的 asctime ⽅法
import time
print(time.asctime())

# 44.将秒数转为时间数组
## ⽤ time 模块⾥的 localtime ⽅法
print(time.localtime())
print(time.localtime(18888888888))

# 45.将时间元组转换为从新纪元后的秒数
## ⽤ time 模块⾥的 mktime ⽅法
print(time.mktime((2020, 7, 3, 21, 48, 56, 4, 21, 0)))

# 46.将字符串转为时间元组
## ⽤ time 模块⾥的 strptime ⽅法
print(time.strptime('Thu Nov 19 00:05:31 2020'))

# 47.随机打乱列表的顺序
## ⽤ random 模块⾥的 shuffle ⽅法
list9 = list(range(20))
print(list9)

random.shuffle(list9)
print list9

#############################################    Python进阶习题   ###########################################
# 48. ⽤for循环实现把字符串变成Unicode码位的列表
## ord() 函数是 chr() 函数(对于 8 位的 ASCII 字符串)的配对函数,它以一个字符串(Unicode 字符)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值。
st =  '!@#$%^&*'
codes = []
for i in st:
    codes.append(ord(i))
print codes

# 49.⽤列表推导式实现把字符串变成Unicode码位的列表
## ⽤列表推导式实现⽐ for 循环加 append 更⾼效简洁,可读性更好。
st1 = '!@#$%^&*'
codes1 = [ord(s) for s in st]
print(codes1)

# 50.打印出两个列表的笛卡尔积
## 解法1:使⽤⽣成器表达式产⽣笛卡尔积,可以帮忙省掉运⾏ for 循环的开销。
colors = ['blacks', 'white']
sizes = ['S', 'M', 'L']
for tshirt in ('%s %s'%(c, s) for c in colors for s in sizes):
    print tshirt

## 解法2:使⽤ itertools ⾥的 product ⽣成器函数。
import itertools
print(list(itertools.product(['blacks', 'white'], ['S', 'M', 'L'])))

# 51. 可迭代对象拆包时,怎么赋值给占位符
## 我们经常⽤ for 循环提取元组⾥的元素,对于我们不想接收的元素,我们可以⽤占位符 _ 接收。
player_infos = [('Kobe', '24'), ('James', '23'), ('Iverson','3')]
for player_names, _ in player_infos:
    print(player_names)

for _, player_values in player_infos:
    print(player_values)

# 52.Python3 中,⽤什么⽅式接收不确定值或参数
## ⽤ *args 的⽅式,*args 位置可以在任意位置。
# a, b, *c = range(8)
# >>> a, b, c
# (0, 1, [2, 3, 4, 5, 6, 7])

# >>> a, *b, c, d = range(5)
# >>> a,b,c,d
# (0, [1, 2], 3, 4)

# >>> *a, b, c, d = range(5)
# >>> a,b,c,d
# ([0, 1], 2, 3, 4)

# 53.⽤切⽚讲对象倒序
s = 'basketball'
print(s[::-1])

# 54.查看列表的 ID

print(id(list8))

# 55.可变序列⽤*=(就地乘法)后,会创建新的序 列吗?
## 不会,可变序列⽤*=(就地乘法)后,不会创建新的序列,新元素追加到⽼元素上,以列表为例,我们看下新⽼列表的id,相等的。

'''
>>> l = [1, 2, 3]
>>> id(l)
4507939272
>>> l *= 2
>>> l
[1, 2, 3, 1, 2, 3]
>>> id(l)
4507939272
'''

# 56.不可变序列⽤*=(就地乘法)后,会创建新的序列吗?
## 会,不可变序列⽤*=(就地乘法)后,会创建新的序列,以元组为例,我们看下新⽼元组的id,是不同的。
'''
>>> t = (1, 2, 3)
>>> id(t)
4507902240
>>> t *= 2
>>> t
(1, 2, 3, 1, 2, 3)
>>> id(t)
4507632648
'''

#######  究极原因
### 所以,对不可变序列进⾏重复拼接操作的话,效率会很低,因为每次都有⼀个新对象,⽽解释器需要把原来对象中的元素先复制到新的对象⾥,然后再追加新的元素

# 57.关于+=的⼀道谜题
'''
t = (1, 2, [30, 40])
t[2] += [50, 60]
'''

'''
到底会发⽣下⾯4种情况中的哪⼀种?
a. t变成(1, 2, [30, 40, 50, 60])。
b.因为tuple不⽀持对它的元素赋值,所以会抛出TypeError异常。
c.以上两个都不是。
d. a和b都是对的。
答案是d,请看下运⾏结果。
>>> t = (1, 2, [30, 40])
>>> t[2] += [50, 60]
Traceback (most recent call last):
 File "<pyshell#1>", line 1, in <module>
 t[2] += [50, 60]
TypeError: 'tuple' object does not support item assignment
>>> t
(1, 2, [30, 40, 50, 60])

'''

# 58.sort() 和 sorted() 区别
l = [1, 9, 5, 8]
j = l.sort()
k = sorted(l)
print l
print k
### sort() 会就地在原序列上排序,sorted() 新建了⼀个新的序列。
'''
list.sort⽅法会就地排序列表,也就是说不会把原列表复制⼀份。这也是这个⽅法的
返回值是None的原因,提醒你本⽅法不会新建⼀个列表。在这种情况下返回None
其实是Python的⼀个惯例:如果⼀个函数或者⽅法对对象进⾏的是就地改动,那它
就应该返回None,好让调⽤者知道传⼊的参数发⽣了变动,⽽且并未产⽣新的对
象。
'''

# 59.通过 reverse 参数对序列进⾏降序排列
'''
reverse 参数⼀般放在 sorted() ⽅法⾥⾯,reverse 默认值为 False,序列默认升序
排列,降序排列的话需要将 reverse 值设置为 True。
'''
l1 = [8,3,5,1,6,9]
j1 = sorted(l1, reverse=True)
print j1

# 60.numpy 怎么把⼀维数组变成⼆维数组
'''
>>> a = numpy.arange(12)
>>> a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> a.shape = 3, 4
>>> a
array([[ 0, 1, 2, 3],
 [ 4, 5, 6, 7],
 [ 8, 9, 10, 11]])
'''

# 61.快速插⼊元素到列表头部
## 可以通过切⽚指定位置插⼊,头部就是[0:0]
l2 = [1,2,3,4,5,6]
l2[0:0] = 'zhang'
print l2

## 还可以通过 insert() ⽅法插⼊,第⼀个参数是位置的坐标,从 0 开始。
l2.insert(0,'wei')
print l2
'''
在第⼀个元素之前添加⼀个元素之类的操作是很耗时的,因为这些操作会牵扯到移
动列表⾥的所有元素。有没有更⾼效的⽅法?⽤双向队列 deque 类。
deque 类可以指定这个队列的⼤⼩,如果这个队列满员了,还可以从反向端删除过
期的元素,然后在尾端添加新的元素
'''
from collections import deque

dp = deque(range(10), maxlen=15)
print dp
dp.appendleft(-1)
print dp

# 62. 字典的创建⽅法
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'one': 1, 'two': 2, 'three': 3})
print a,b,c,d,e


## ⽤字典推导(dictcomp)构建字典
dial_code = [
 (86, 'China'),
 (91, 'India'),
 (1, 'US'),
 (55, 'Brazil'),
 (7, 'Russia'),
 (81, 'Japan') ]
coutry_code = {coutry:code for code, coutry in dial_code}
print coutry_code

## 63.通过⼀次查询给字典⾥不存的键赋予新值
### ⽤setdefault⽅法,只查询⼀次,效果更快
coutry_code = {'China': 86, 'India': 91, 'US': 1, 'Brazil': 55,
'Russia': 7, 'Japan': 81}
coutry_code.setdefault('china', []).append(86)
print coutry_code
### 如果⽤下⾯这种⽅法,需要查询三次
if 'china' not in coutry_code:
 coutry_code['china'] = []
 coutry_code['china'].append(86)
print(coutry_code)

'''
像k in my_dict.keys( )这种操作在Python 3中是很快的,⽽且即便映射类型对
象很庞⼤也没关系。这是因为dict.keys( )的返回值是⼀个“视图”。视图就像⼀
个集合,⽽且跟字典类似的是,在视图⾥查找⼀个元素的速度很快。在“Dictionary
view objects”⾥可以找到关于这个细节的⽂档。Python 2的dict.keys( )返回的
是个列表,因此虽然上⾯的⽅法仍然是正确的,它在处理体积⼤的对象的时候效率
不会太⾼,因为k in my_list操作需要扫描整个列表。
'''

## 64.统计字符串中元素出现的个数?
## ⽤collections中的Counter⽅法统计,返回的结果是对应元素和个数形成的键值对。
import collections
ct = collections.Counter('adcfadcfgbsdcv')
print ct

'''
怎么统计出排名前n的元素?
⽤most_common⽅法,参数⾥填n,⽐如前两名的话
'''
cd = ct.most_common(2)
print cd

## 65.列表去重
l3 =  ['A', 'B', 'A', 'B']
ll3 = list(set(l3))
print ll3

# 66.求m中元素在n中出现的次数
## 基础解法:
m = {'A', 'B', 'C'}
n = {'B', 'C', 'D'}
found = 0
for i in m:
    if i in n:
        found += 1
print found

## ⾼级解法:
print(len(m&n))

### 如果m和n不是集合的话,直接转换后再取交集
print(len(set(m) & set(n)))
## ⾼级解法的另⼀种写法:
print( len(set(m).intersection(n)))

# 67. 新建⼀个Latin-1字符集合,该集合⾥的每个字符的Unicode名字⾥都有“SIGN”这个单词,⽤集合推导式完成。
from unicodedata import name
# print ({chr(i) for i in range(32, 256) if 'SIGN' in name(chr(i), '')})

# 68. 查询系统默认编码⽅式
import sys
sys.path.append('./')
fp = open('test.txt', 'w')
print fp.encoding

# 修改编码方式
#fp = open('test.txt', 'w', encoding='utf-8')
#print fp.encoding

# 69. ⽤递归实现阶乘
def factorial(n):
 """:return n!"""
 return 1 if n < 2 else n * factorial(n-1)
fa  = factorial(10)
print fa

# 70. all([])的输出结果是多少?
True

# 71.  any([])的输出结果是多少?
False

# 72.判断对象是否可被调⽤?
#⽤ Python 内置的函数 callable() 判断
print [callable(obj) for obj in (abs, str, 2)]

# 73.列出对象的所有属性
## 使⽤ dir 函数来获取对象的所有属性。
import requests
print(dir(requests))

# 74.怎么得到类的实例没有⽽函数有的属性列表
## 创建⼀个空的⽤户定义的类和空的函数,计算差集,然后排序。
class C:
  pass

obj = C()
def func():
  pass

print sorted(set(dir(func)) - set(dir(obj)))

# 75.函数中,不想⽀持数量不定的定位参数,但是想⽀持仅限关键字参数,参数怎么定义
## 那就要在关键字参数前加⼀个 *。
def f(a, **b):
  return a,b
ff = f(1, b=2)
print ff
# 这样的话,b 参数强制必须传⼊实参,否则会报错

# 76.怎么给函数参数和返回值注解
'''
代码执⾏时,注解不会做任何处理,只是存储在函数的__annotations__属性(⼀个
字典)中
'''
## def function(text: str, max_len: 'int > 0' = 80) -> str:

'''
函数声明中的各个参数可以在:之后增加注解表达式。如果参数有默认值,注解放在
参数名和=号之间。如果想注解返回值,在)和函数声明末尾的:之间添加->和⼀个表
达式。
Python对注解所做的唯⼀的事情是,把它们存储在函数的__annotations__属性⾥。
仅此⽽已,Python不做检查、不做强制、不做验证,什么操作都不做。换句话说,
注解对Python解释器没有任何意义。注解只是元数据,可以供IDE、框架和装饰器
等⼯具使用
'''
# 77.不使⽤递归,怎么⾼效写出阶乘表达式
## 通过 reduce 和 operator.mul 函数计算阶乘
from functools import reduce
from operator import mul
def fact(n):
  return reduce(mul, range(1, n+1))
fa = fact(5)
print fa

# 78.Python什么时候执⾏装饰器?
## 函数装饰器在导⼊模块时⽴即执⾏,⽽被装饰的函数只在明确调⽤时运⾏。这突出了Python程序员所说的导⼊时和运⾏时之间的区别。


# 79.判断下⾯语句执⾏是否会报错?
'''
>>> b = 3
>>> def fun(a):
      print(a)
      print(b)
      b = 7
 
>>> fun(2)

会报错,Python编译函数的定义体时,先做了⼀个判断,那就是 b 是局部变量,因
为在函数中给它赋值了。但是执⾏ print(b) 时,往上⼜找不到 b 的局部值,所以会
报错
Python 设计如此,Python 不要求声明变量,但是假定在函数定义体中赋值的变量
是局部变量。

2
Traceback (most recent call last):
 File "<pyshell#50>", line 1, in <module>
 fun(2)
 File "<pyshell#49>", line 3, in fun
 print(b)
UnboundLocalError: local variable 'b' referenced before assignment
'''
# 80.怎么强制把函数中局部变量变成全局变量
## ⽤ global 声明
'''
>>> b = 3
>>> def fun(a):
      global b
      print(a)
      print(b)
      b = 7
>>> b = 5
>>> fun(2) 
2
5
'''
# 81.闭包中,怎么对数字、字符串、元组等不可变元素更新
## 我们知道,在闭包中,声明的变量是局部变量,局部变量改变的话会报错。
'''
>>> def make_averager():
      count = 0
      total = 0
   def averager (new_value):
      count += 1
      total += new_value
      return total / count
   return averager
>>> avg = make_averager()
>>> avg(10)
Traceback (most recent call last):
 File "<pyshell#63>", line 1, in <module>
 avg(10)
 File "<pyshell#61>", line 5, in averager
 count += 1
UnboundLocalError: local variable 'count' referenced before
assignment

为了解决这个问题,Python 3引⼊了 nonlocal 声明。它的作⽤是把变量标记为⾃由
变量

'''

'''
>>> def make_averager():
      count = 0
      total = 0
   def averager (new_value):
      nonlocal count, total
      count += 1
      total += new_value
      return total / count
   return averager

>>> avg = make_averager()
>>> avg(10)
10.0
'''

# 82.Python2 怎么解决访问外部变量报错的问题
'''
https://www.python.org/dev/peps/pep-3104/
'''

# 83.测试代码运⾏的时间
## ⽤ time 模块⾥的 perf_counter ⽅法
'''
python2.7 不支持该种写法,python3 支持
import time
t0 = time.perf_counter()
for i in range(1000):
  pass

t1 = time.perf_counter()
print t1 - t0
'''
## 或者,直接⽤ time.time()

t2 = time.time()
for i in range(1000):
  pass
t3 = time.time()

print t3 - t2


# 84. 怎么优化递归算法,减少执⾏时间
## 使⽤装饰器 functools.lru_cache() 缓存数据, 同样适用于python3以上版本
'''
import functools
@functools.lru_cache()
def fibonacci(n):
  if n < 2:
    return n 
  return fibonacci(n-2)+fibonacci(n-1)
print fibonacci(6)

标准库singledispatch官⽅⽂档:https://www.python.org/dev/peps/pep-0443/
'''
# 85. ⽐较两个对象的值(对象中保存的数据)是否相 等
## ⽤ == 运算符⽐较
l6 = [1,2,3]
l7 = [1,2,3]
print l6==l7

# 86.⽐较两个对象的内存地址 id 是否相等
## ⽤ is ⽐较,ID⼀定是唯⼀的数值标注,⽽且在对象的⽣命周期中绝不会变
print l6 is l7

# 87.怎么格式化显示对象?
'''
可以⽤内置的 format( )函数和str.format( )⽅法。
format(my_obj, format_spec)的第⼆个参数,或者str.format( )⽅法的格式字符
串,{}⾥代换字段中冒号后⾯的部分。
'''
from datetime import datetime
now = datetime.now()
print format(now,'%H:%M:%S')
form =  "It's now {:%I:%M%p}".format(now)
print form

# 88.复制⼀个序列并去掉后 n 个元素
'''
可能有同学会想到⽤ pop(),但这个⽅法会就地删除原序列,不会复制出⼀个新的
序列。
可以⽤切⽚的思想,⽐如复制后去掉后两个元素
'''
l8 = [1,2,3,4,5]
j2 = l8 [:-2]
print j2


# 89.Python中怎么定义私有属性。
## 在属性前加两个前导下划线,尾部没有或最多有⼀个下划线

# 90. 怎么随机打乱⼀个列表⾥元素的顺序
## ⽤ random ⾥的 shuffle ⽅法
from random import shuffle
l9 = list(range(30))
shuffle(l9)
print l9

# 91. 怎么判断某个对象或韩式是⼀个已知的类型
## ⽤ Python 的内置函数 isinstance() 判读
print  isinstance('aa', str)

# 92. 怎么打印出分数
## ⽤ fractions 中的 Fraction ⽅法
from fractions import Fraction
print Fraction(1,3)

# 93.  + 和 += 区别
## 两边必须是同类型的对象才能相加,+= 右操作数往往可以是任何可迭代对象。
l0  = list(range(6))
l0 += 'qwer'
print l0

'''
 j = l0 + (6, 7)
Traceback (most recent call last):
 File "<pyshell#91>", line 1, in <module>
 j = l0 + (6, 7)
TypeError: can only concatenate list (not "tuple") to list
'''
# 94. 怎么列出⼀个⽬录下所有的⽂件名和⼦⽂件名
## ⽤ os.walk ⽣成器函数,我⽤ site-packages ⽬录举例
import os
dirs = os.walk('/home/zhangweijian/PythonProject/prac_one')
for dir in dirs:
  print dir

# 95.返回 1 到 10 的阶乘列表
## ⾼效的⽅法需要⽤到 itertools 和 operator 模块,导包后⼀⾏代码搞定。
import itertools
import operator
# print  list(itertools.accumulate(range(1, 11), operator.mul))

# 96.怎么快速拼接字符串和序列形成新的列表
## ⽤ itertools ⾥的 chain ⽅法可以⼀⾏代码搞定
import itertools
print list(itertools.chain('ABC', range(5)))


# 97. 进度条显示
## ⽤ tqdm 库

import time
from tqdm import tqdm
for i in tqdm(range(1000)):
  time.sleep(.01)






  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值