Python技巧100题(七)

在这里插入图片描述

1.sort()和sorted()的区别

l = [1, 9, 5, 8]
j = l.sort()
k = sorted(l)
sort()会在原序列上排序,sorted()新建了一个新的序列

2.怎么通过reverse参数对序列进行降序排列

reverse一般放在sorted()方法里面,reverse默认值位False,
序列默认升序排列,降序排列的话需要将reverse值设置为True

l = [1, 9, 5, 8]
j = sorted(l, reverse=True)
print(j)
[9, 8, 5, 1]

3.numpy怎么把一维数组变成二维数组

a = numpy.arange(12)
print(a)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
a.shape = 3, 4
print(a)
array([[0, 1, 2, 3], 
      [4, 5, 6, 7],
      [8, 9, 10, 11]])

4.快速插入元素到列表头部

l = [1, 2, 3, 4, 5]
l[0:0] = 'Python'
print(l)
['P', 'y', 't', 'h', 'o', 'n', 1, 2, 3, 4, 5]

l = [1, 2, 3, 4, 5]
l.insert(0, 'first')
print(l)
['first', 1, 2, 3, 4, 5]

from collections import deque
dp = deque(range(10), maxlen=15)
print(dq)
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=15)
dp.appendleft(-1)
print(dq)
deque([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=15)

5.字典的创建方法

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([('tow', 2), ('one', 1), ('three', 3)])
e = dict({'one': 1, 'two': 2, 'three': 3})

6.通过一次查询给字典里不存在的键赋予新值

coutry_code = {'China': 86, 'India': 91, 'US': 1, 'Brazil': 55,
                'Russia': 7, 'Japan': 81}
coutry_code.setdefault('china', []).append(86)
if 'china' not in coutry_code:
    coutry_code['china'] = []
    coutry_code['china'].append(86)
print(coutry_code)                   

7.统计字符串中元素出现的个数

import collections
c = collections.Counter('adcfadcfgbsdcv')
print(c)
Counter({'d': 3, 'c': 3, 'a': 2, 'f': 2, 'g': 1, 'b': 1, 's': 1, 'v': 1})
//统计排名前n的元素
print(c.most_common(2))
[('d', 3), ('c', 3)]

8.列表去重

l = [1,2,3,4,5,6,6,5,4,3,2,1]
//使用字典的fromkeys()和keys方法
//fromkeys()方法去重,去重后获得元素为键,值为None的字典
//key()方法,返回以字典的键为元素的类列表
d = {}
l = d.fromkeys(l)
print(l)
{1: None, 2: None, 3: None, 4: None, 5: None, 6: None}
l = l.keys()
print(l)
dict_keys([1, 2, 3, 4, 5, 6])
l = list(l)
print(l)
[1, 2, 3, 4, 5, 6]

//使用set()函数
//set()函数创建一个无序不重复元素集,可以删除重复数据
l2 = [1,2,3,4,5,6,6,5,4,3,2,1]
l2 = set(l2)
print(l2)
{1, 2, 3, 4, 5, 6}
l2 = list(l2)
print(l2)
[1, 2, 3, 4, 5, 6]

//使用for循环
l3 = [1,2,3,4,5,6,6,5,4,3,2,1]
l4 = []
for x in l3;
    if x not in l4:
        l4.append(x)
print(l4)
[1, 2, 3, 4, 5, 6]        

9.求m中元素在n中出现的次数

m = {'A', 'B', 'C'}
n = {'B', 'C', 'D'}
find = 0
for i in m:
    if i in n:
        find += 1
print(find)       
2

m = {'A', 'B', 'C'}
n = {'B', 'C', 'D'}
print(len(m & n))
2

10.新建一个Latin-1字符集合,该集合里的每个字符的Unicode名字里都有SIGN这个单词,用集合推导式完成。

from unicodedata import name
print({chr(i) for i in range(32, 256) if 'SIGN' in name(chr(i), '')})
{'®', '±', '×', '>', '÷', '+', '¶', '<', '$', '©', '=', '%', '#', '§', '°', '¥', '¢', '¬', '£', '¤', 'µ'}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值