Python 一点基本技巧

Python 一点基本技巧

Python合并列表,append()、extend()、+、+=

实际应用中涉及到了列表合并的问题。

在应用append()时,发现列表是以一个元素的形式追加到列表上的,最后查询后用的是extend()方法,下面是区别

1.append()向列表尾部追加一个新元素,列表只占一个索引位,在原有列表上增加

2.extend() 向列表尾部追加一个列表,将列表中的每个元素都追加进来,在原有列表上增加

3.+ 直接用+号看上去与用extend()一样的效果,但是实际上是生成了一个新的列表存这两个列表的和,只能用在两个列表相加上

4.+= 效果与extend()一样,向原列表追加一个新元素,在原有列表上增加

列表python - 列表分组技巧

#请写出一段 Python 代码实现分组一个 list 里面的元素,如 [1,2,3,…100]变成 [[1,2,3],[4,5,6]….]

1
2
3
4
5
6
a = [x for x in range(1,101)] 

b = [a[i:i+3] for i in range(0, len(a),3)]

print(b)

运行结果:

1
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 23, 24], [25, 26, 27], [28, 29, 30], [31, 32, 33], [34, 35, 36], [37, 38, 39], [40, 41, 42], [43, 44, 45], [46, 47, 48], [49, 50, 51], [52, 53, 54], [55, 56, 57], [58, 59, 60], [61, 62, 63], [64, 65, 66], [67, 68, 69], [70, 71, 72], [73, 74, 75], [76, 77, 78], [79, 80, 81], [82, 83, 84], [85, 86, 87], [88, 89, 90], [91, 92, 93], [94, 95, 96], [97, 98, 99], [100]] 

实际应用的一段代码

1
2
full_list_info = [n[i] for n in dic_info for i in Head_info] #全部信息组成为一个列表
five_elment_list = [full_list_info[i:i + len(Head_info)] for i in range(0, len(full_list_info), len(Head_info))] #5个元素为一组列表

运行效果如下:

1
2
3
4
['1', 'tu', '121', '13651054608', 'IT', '2', 'hh', '23', '13304320533', 'Tearcher', '3', 'nezha', '25', '1333235322', 'IT', '9', 'xiaohaha', '121', '17601234567', 'IT', '10', 'tudou', '21', '1760123', 'ban', '11', 'xiaohaha', '50', '138', 'game', '12', 'mantou25000', '23', '17602323312', '搬砖', '13', '32', '23', '23', '3', '14', '12', '123', '32', '132']

#分组后效果
[['1', 'tu', '121', '13651054608', 'IT'], ['2', 'h', '23', '13304320533', 'Tearcher'], ['3', 'nezha', '25', '1333235322', 'IT'], ['9', 'xiaohaha', '121', '17601234362', 'IT'], ['10', 'tudou', '21', '1760123', 'ban'], ['11', 'xiaohaha', '50', '138', 'game'], ['12', 'mantou25000', '23', '17602323312', '搬砖'], ['13', '32', '23', '23', '3'], ['14', '12', '123', '32', '132']]

###变量值交换

1
2
3
4
5
""""pythonic way of value swapping"""

a,b = 5,10
a,b = b,a

拼接列表中字符串

1
2
3
4

li = ['he','llo','world','python']

print(''.join(li)

也可以使用’+’ ,join效率更高

查找中出现频繁的元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

a = [1, 2, 3, 3, 4, 5, 2313, 13, 123, 4, 4, 4, 99, 9, 9, 0, 33, 11, 1, 2, 2, 3, 4, 4, 5, 5, 5, 5, 55, 5, 5, 5, 6, 6, 6,6, 66]

print(set(a))
print(a.count(4))

# 一
litu = [(i, a.count(i)) for i in a]
maxel = max(litu, key=lambda x: x[1])
print(maxel)

mmm = map(a.count, a)
print(list(mmm))

# 一
maxel = max(zip(map(a.count, a), a))
print(maxel)
print('..')

# 二
maxel2 = max([(i, a.count(i)) for i in a], key=lambda x: x[1])
print(maxel2)

# 三
maxel3 = max(a, key=lambda x: a.count(x))
print(maxel3)

# 四
print(max(set(a), key=a.count))

# 五
from collections import Counter

cnt = Counter(a)
print(cnt.most_common()) # ??

检查两个字符串是否相同的字符构成

1
2
3
4
5
6
from collections import Counter
str1 = '13'
str2 = '13'
islike = Counter(str1) == Counter(str2)
print(islike)

字符串反转

1
2
3
4
5
6
7
8
9
10
11
a = [5,4,3,2,1]

#一
print(a[::-1])

#二
b = [i for i in reversed(a)]
print(b)

for i in reversed(a):
print(i)

列表有个reverse方法,也是反转列表,但是它是对原列表进行反转,而不是返回一个新的列表

转置二维数组

1
2
3
4
5
6
#transpose 2d array

original = [['a','b'],['c','d'],['e','f']]
transposed = zip(*original)
print(list(transposed))

链式比较

1
2
3
4
#chained comparison with all kind of operators
b = 6
print(4 < b < 7)
print(1 == b < 2)

链式函数调用

1
2
3
4
5
6
7
8
9
10
11
12
#calling different functions with same arguments based on condition

def product(a,b):
return a * b


def add(a,b):
return a + b

b = True

print((product if b else add)(5,7))

拷贝列表

1
2
3
4
5
6
7
8
9
10
11
浅拷贝
a.copy()

a[::]

深拷贝

from copy import deepcopy

deepcopy(l)

字典get

1
2
3
4
5

#returning None or default value,when key is not in dict

d = {'a':1,'b':2}
print(d.get('c','xiaohaah'))

按字典值排序

习题中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

dicton = [
{
'name': 'IBM', 'shares': 100, 'price': 91.1}, {
'name': 'AAPL', 'shares': 50, 'price': 543.22}, {
'name': 'FB', 'shares': 200, 'price': 21.09}, {
'name': 'HPQ', 'shares': 35, 'price': 31.75}, {
'name': 'YHOO', 'shares': 45, 'price': 16.35}, {
'name': 'ACME', 'shares': 75, 'price': 115.65}]


sortd = sorted(dicton,key= lambda x:x['price'])

print(sortd)


示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#sort a dictonary by its values with the built-in functions and a 'key' argument

d = {'apple':10,'orange':20,'banana':5,'tomatol':1,'baozi':100}
for i in d.items():
print(i[0],i[1])

print(sorted(d.items(),key=lambda x:x[1]))

#sort using operator itemgetter as the sort key instead or a lambda

from operator import itemgetter

print(sorted(d.items(),key=itemgetter(1)))

sort dict key by value
#pythonic******* 真棒
print(sorted(d,key=d.get))

for else 不太推荐

else gets called when for loop does not reach break statement

1
2
3
4
5
6
7
8
9
a = [1,2,3,4,5]

for el in a:
if el == 0:
break
else:
print('did not break out of for loop')


将列表转换成用逗号分隔的字符串

1
2
3
4
5
6
7
items = ['foo','hello','python']

print(','.join(items))

unmber = [2,3,5,10]

print(','.join(map(str,unmber)))

合并字典

1
2
3
4
5
6
7
8
9
10
11
12
13
d1 = {'a':1}
d2 = {'b':2}

#pyton3.5
#1.
print({**d1,**d2})

#2.
print(dict(d1.items()|d2.items()))

#3.
d1.update(d2)
print(d1)

获取列表中最大值与最小值的索引位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
lst = [55,50,66,100,28,80]
print(list(map(lst.index,lst)))

print(map((lst[lst.index],lst.index),lst))
print(min(map(lst.index,lst),key=lambda x:x[0]))




def minindex(lst):
mmm =min(map((a.index,i),lst),key=lambda x:x[1])
print(mmm)

print(min)


minindex(lst)

def maxindex(lst):
return max(range(len(lst)),key=lst.__getitem__)

print(maxindex(lst))

移除列表中重复的元素

1
2
3
4
5
6
7
8
9
10
ites= [2222,3,3,3,3,4,4,4]

newite = list(set(ites))
print(newite)

#romve dups add keey order

from collections import OrderedDict

print(OrderedDict.fromkeys(items).keys())

参考连接


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!