a = [[1, 2], [3, 4], [5, 6]]
x = [j for i in a for j in i] #方法一
import numpy as np
b = np.array(a).flatten().tolist() #方法二
a = 1.3333333
b = "%.03f"%a #保留三位小数
print(b)
c = round(a, 2) #保留两位小数
print(c)
生成器是特殊的迭代器,
a = (i for i in range(3))
print(a)
<generator object <genexpr> at 0x000000C660EB65C8>
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
#交集
j1 = [i for i in a if i in b]
j2 = list(set(a).intersection(set(b)))
#并集
b = list(set(a).union(set(b)))
#差集
c1 = list(set(b).difference(set(a))) #b中有而a中没有,反之转换a,b即可
dec = int(input("请输入一个十进制数字:"))
print("十进制为:", dec)
print("二进制为", bin(dec))
print("八进制为:", oct(dec))
print("十六进制为", hex(dec))
>>> a, b = 'hello', ' world'
>>> a + b
'hello world'
print('{}{}'.format('hello', ' world')
print('-'.join(['aa', 'bb', 'cc']))
>>> aa, bb = 'hello', 'world'
>>> f'{aa} {bb}'
'hello world'
>>> aa = 'hello '
>>> aa * 3
'hello hello hello '
#最垃圾的获取字典中需要的键的数据
>>> cowboy = {'age': 32, 'horse': 'mustang', 'hat_size': 'large'}
>>> if 'name' in cowboy:
... name = cowboy['name']
... else:
... name = 'The Man with No Name'
...
>>> name
'The Man with No Name'
#获取响应键值,如果有则返回,没有则返回后面的字符
>>> name = cowboy.get('name', 'The Man with No Name')
#取响应键值,如果有则返回,没有则设置此键并以后面的数据作为内容,并返回
>>> name = cowboy.setdefault('name', 'The Man with No Name')
a = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]
a = sorted(a, key = lambda x:(x<0, abs(x)))
print(a)
[0, 2, 4, 8, 8, 9, -2, -4, -4, -5, -20]
foo = [{"name":"zs","age":19},{"name":"ll","age":54},
{"name":"wa","age":17},{"name":"df","age":23}]
a = sorted(foo, key = lambda x:x["age"], reverse=False) #年龄从大到小排序
b = sorted(foo, key = lambda x:x["name"])#姓名从小到大排序
foo = [("zs", 19), ("ll", 54), ("wa", 17), ("sf", 23)]
a = sorted(foo, key=lambda x:x[1], reverse=True) #按年龄从大到小
print(a)
b = sorted(foo, key = lambda x:x[0])#按姓名首字母从小到大
print(b)
[('ll', 54), ('sf', 23), ('zs', 19), ('wa', 17)]
[('ll', 54), ('sf', 23), ('wa', 17), ('zs', 19)]
foo = [["zs", 19], ["ll", 54], ["wa", 23], ["df", 23], ["xf", 23]]
a = sorted(foo, key = lambda x:(x[1], x[0]), reverse=False) #年龄相同时,添加参数按照字母排序
print(a)
[['zs', 19], ['df', 23], ['wa', 23], ['xf', 23], ['ll', 54]]
dic = {"name":"zs", "sex":"man", "city":"bj"}
#方法一,zip函数
a1 = zip(dic.keys(), dic.values()) #字典转化为元组对象
print(a1) #
a1 = [i for i in a1] #生成器取出元素
print(a1) #[('name', 'zs'), ('sex', 'man'), ('city', 'bj')]
b1 = sorted(a1, key = lambda x:x[0]) #依据元素的第一个元素进行排序,即根据键进行排序
print(b1) #[('city', 'bj'), ('name', 'zs'), ('sex', 'man')]
new_dic = {i[0]:i[1] for i in b1}#还原排序好的字典
print(new_dic) #{'city': 'bj', 'name': 'zs', 'sex': 'man'}
#方法二,不用zip
print(dic.items()) #字典转化为列表嵌套元组(不在原字典上进行操作)
b2 = sorted(dic.items(), key = lambda x:x[0])
new_dic = {i[0]:i[1] for i in b1}#还原排序好的字典
print(new_dic) #{'city': 'bj', 'name': 'zs', 'sex': 'man'}
s = ["ab", "abc", "a", "abcd"]
a = sorted(s, key = lambda x:len(x))
print(a)
s.sort(key=len) #在原列表上进行更改
print(s)
['a', 'ab', 'abc', 'abcd']
['a', 'ab', 'abc', 'abcd']
list = [1, 2, 3, 4, 5]
def fn():
return x**2
res = map(fn, list)
#res = 1, 4, 9, 16, 25
import random
import numpy as np
result = random.randint(10, 20)
res = np.random.randn(5)
ret = random.random()
/*
15
[-0.53466153 0.69176947 0.18377477 0.47902627 0.93834969]
0.6697961508083531
*/
from collections import Counter
a = "kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h"
res = Counter(a)
print(res)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def fn(a):
return a%2 == 1
new_list = filter(fn, a) #生成的是一个构造器对象,需要单个取出
new_list = [i for i in new_list]
print(new_list)
import os
[d for d in os.listdir('.')]
import os
def print_dir():
filepath = input("请输入一个路径:")
if filepath == '':
print("请输入正确路径")
else:
for i in os.listdir(filepath):
print(os.path.join(filepath, i))
print_dir()
import os
def print_dir(filepath):
for i in os.listdir(filepath):
path = os.path.join(filepath, i)
if os.path.isdir(path):
print_dir(path)
if path.endswith('.py'):
print(path)
filepath = '.'
print_dir(filepath)
“”“假如你有一长串没有标点符号或大写字母的单词,你想要计算每个单词出现的次数。”“”
#collections.Counter提供了一种更清晰,更方便的方法
>>> from collections import Counter
>>> words = "if there was there was but if
... there was not there was not".split()
>>> counts = Counter(words)
>>> counts
Counter({'if': 2, 'there': 4, 'was': 4, 'not': 2, 'but': 1})
#如果你好奇两个最常见的词是什么?只需使用.most_common()
>>> counts.most_common(2)
[('there', 4), ('was', 4)]
#当你需要列出一个列表中所有可能的搭配组合
#不在乎顺序,会存在重复
>>> import itertools
>>> friends = ['Monique', 'Ashish', 'Devon', 'Bernie']
>>> list(itertools.permutations(friends, r=2))
[('Monique', 'Ashish'), ('Monique', 'Devon'), ('Monique', 'Bernie'),
('Ashish', 'Monique'), ('Ashish', 'Devon'), ('Ashish', 'Bernie'),
('Devon', 'Monique'), ('Devon', 'Ashish'), ('Devon', 'Bernie'),
('Bernie', 'Monique'), ('Bernie', 'Ashish'), ('Bernie', 'Devon')]
#不希望重复(不会前后重复)
>>> list(itertools.combinations(friends, r=2))
[('Monique', 'Ashish'), ('Monique', 'Devon'), ('Monique', 'Bernie'),
('Ashish', 'Devon'), ('Ashish', 'Bernie'), ('Devon', 'Bernie')]