-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathpython.datastruct.html
More file actions
583 lines (421 loc) · 18.8 KB
/
Copy pathpython.datastruct.html
File metadata and controls
583 lines (421 loc) · 18.8 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>1.8. 数据结构</title><link rel="stylesheet" type="text/css" href="../docbook.css" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><meta name="keywords" content="php,pear,pecl,phar, python, , " /><link rel="home" href="../index.html" title="Netkiller Python 手札" /><link rel="up" href="index.html" title="第 1 章 Python 入门" /><link rel="prev" href="type.html" title="1.7. 数据类型" /><link rel="next" href="python.serializable.html" title="1.9. 序列化" /></head><body><a xmlns="" href="//www.netkiller.cn/">Home</a> | <a xmlns="" href="//netkiller.github.io/">简体中文</a> | <a xmlns="" href="http://netkiller.sourceforge.net/">繁体中文</a> | <a xmlns="" href="/journal/index.html">杂文</a>
| <a xmlns="" href="https://github.com/netkiller">Github</a> | <a xmlns="" href="https://zhuanlan.zhihu.com/netkiller">知乎专栏</a> | <a xmlns="" href="https://www.facebook.com/bg7nyt">Facebook</a> | <a xmlns="" href="http://cn.linkedin.com/in/netkiller/">Linkedin</a> | <a xmlns="" href="https://www.youtube.com/user/bg7nyt/videos">Youtube</a> | <a xmlns="" href="//www.netkiller.cn/home/donations.html">打赏(Donations)</a> | <a xmlns="" href="//www.netkiller.cn/home/about.html">About</a><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">1.8. 数据结构</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="type.html">上一页</a> </td><th width="60%" align="center">第 1 章 Python 入门</th><td width="20%" align="right"> <a accesskey="n" href="python.serializable.html">下一页</a></td></tr></table><hr /></div><table xmlns=""><tr><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&repo=netkiller.github.io&type=watch&count=true&size=large" height="30" width="170" frameborder="0" scrolling="0" style="width:170px; height: 30px;" allowTransparency="true"></iframe></td><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&repo=netkiller.github.io&type=fork&count=true&size=large" height="30" width="170" frameborder="0" scrolling="0" style="width:170px; height: 30px;" allowTransparency="true"></iframe></td><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&type=follow&count=true&size=large" height="30" width="240" frameborder="0" scrolling="0" style="width:240px; height: 30px;" allowTransparency="true"></iframe></td><td></td><td><a href="https://zhuanlan.zhihu.com/netkiller"><img src="/images/logo/zhihu-card-default.svg" height="25" /></a></td><td valign="middle"><a href="https://zhuanlan.zhihu.com/netkiller">知乎专栏</a></td><td></td><td></td><td></td><td></td></tr></table><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="python.datastruct"></a>1.8. 数据结构</h2></div></div></div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="data.list"></a>1.8.1. List</h3></div></div></div>
<p>随机抽取list成员</p>
<pre class="screen">
import random
# random choice from a list
for i in range(5):
print random.choice([1, 2, 3, 5, 9])
</pre>
<pre class="programlisting">
test = []
test.append('1')
test.append('b')
test.append('c')
print(test)
</pre>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id872"></a>1.8.1.1. 返回索引序号</h4></div></div></div>
<p>index()方法语法:</p>
<pre class="screen">
list.index(x[, start[, end]])
参数
x-- 查找的对象。
start-- 可选,查找的起始位置。
end-- 可选,查找的结束位置。
</pre>
<pre class="programlisting">
fruits = ["apple", "banana", "cherry", "apple"]
print(fruits.index("apple")) # 输出: 0
animals = ["cat", "dog", "tiger"]
print(animals.index("dog")) # 输出: 1
numbers = [1, 2, 3, 4, 1, 1, 1, 4, 5]
print(numbers.index(4, 4, 8)) # 输出: 7
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id873"></a>1.8.1.2. 二维列表,指定列,查找最大值</h4></div></div></div>
<pre class="programlisting">
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
column = [row[1] for row in matrix]
max_value = max(column)
print("第二列最大值:", max_value)
</pre>
<p>返回最大值</p>
<pre class="programlisting">
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
column = [row[1] for row in matrix]
max_value = max(column)
index = column.index(max_value)
print(index, matrix[index])
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="list.index"></a>1.8.1.3. 获得list中最大/最小值元素的索引</h4></div></div></div>
<pre class="programlisting">
获得list中最大元素的索引
nums = [1,2,3,4,5]
nums.index(max(nums))
相应的最小值索引
nums = [1,2,3,4,5]
nums.index(min(nums))
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="list.enumerate"></a>1.8.1.4. 用 enumerate 返回 list 索引</h4></div></div></div>
<pre class="programlisting">
>>> seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
</pre>
<p>指定开始索引下标</p>
<pre class="programlisting">
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id874"></a>1.8.1.5. 二维列表 LIST 排序</h4></div></div></div>
<pre class="screen">
# 定义一个二维列表
lst = [[4, 2], [1, 5], [3, 3], [2, 1]]
# 使用sorted()函数和lambda表达式按照二维列表的第一列进行排序
sorted_lst = sorted(lst, key=lambda x: x[0])
print(sorted_lst)
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id875"></a>1.8.1.6. 列表相减运算</h4></div></div></div>
<pre class="screen">
a = ['a', 'b', 'c', 'd']
b = ['b', 'c']
# 方法1:使用列表推导式(简洁高效)
result = [x for x in a if x not in b]
print("方法1结果:", result) # 输出: ['a', 'd']
# 方法2:使用filter函数(函数式编程风格)
result = list(filter(lambda x: x not in b, a))
print("方法2结果:", result) # 输出: ['a', 'd']
# 方法3:循环遍历(原地修改原列表,不推荐但适合理解过程)
a_copy = a.copy() # 复制原列表避免遍历中修改导致的问题
for item in a_copy:
if item in b:
a.remove(item)
print("方法3结果:", a) # 输出: ['a', 'd']
</pre>
</div>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="data.set"></a>1.8.2. Set 集合</h3></div></div></div>
<pre class="programlisting">
>>> ','.join(set);
'four,three,two,one'
>>> set('four,three,two,one'.split(','));
{'one', 'four', 'three', 'two'}
>>> fruit = [ 'banana', 'orange', 'pineapple' ]
>>> set(fruit)
{'banana', 'pineapple', 'orange'}
</pre>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id876"></a>1.8.2.1. 创建集合</h4></div></div></div>
<pre class="programlisting">
>>> set = {'a','b','c'}
>>> set
set(['a', 'c', 'b'])
>>> set = {"one", "two", "three","one"}
>>> set
set(['three', 'two', 'one'])
</pre>
<pre class="programlisting">
set1 = {1, 2, 3, 4}
print(set1)
set2 = set([4, 5, 6, 7])
print(set2)
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id877"></a>1.8.2.2. 添加元素</h4></div></div></div>
<p>添加元素到集合有两个方法,分别是 add() 和 update()</p>
<pre class="programlisting">
>>> set.add('four')
>>> set
set(['four', 'three', 'two', 'one'])
</pre>
<pre class="programlisting">
company = set(("Google", "OpenAI", "Facebook"))
company.update({"Microsoft"})
company.update({"Aliyun","Taobao"})
print(company)
company.update([1,2],[5,6])
print(company)
</pre>
<pre class="screen">
{'Facebook', 'Google', 'Microsoft', 'Taobao', 'Aliyun', 'OpenAI'}
{'Facebook', 1, 2, 5, 6, 'Aliyun', 'Google', 'OpenAI', 'Microsoft', 'Taobao'}
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id878"></a>1.8.2.3. 删除元素</h4></div></div></div>
<pre class="programlisting">
company = set({'Facebook', 'Google', 'Microsoft', 'Taobao', 'Aliyun', 'OpenAI'})
print(company)
company.remove("OpenAI")
print(company)
company.discard("Aliyun")
print(company)
</pre>
<p>随机移除一个元素</p>
<pre class="programlisting">
company.pop()
print(company)
</pre>
<p></p>
<pre class="screen">
{'Taobao', 'Facebook', 'Aliyun', 'Microsoft', 'OpenAI', 'Google'}
{'Taobao', 'Facebook', 'Aliyun', 'Microsoft', 'Google'}
{'Taobao', 'Facebook', 'Microsoft', 'Google'}
{'Facebook', 'Microsoft', 'Google'}
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id879"></a>1.8.2.4. 清空集合</h4></div></div></div>
<pre class="programlisting">
>>> company = set(("Google", "Microsoft", "OpenAI"))
>>> company.clear()
>>> print(company)
set()
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id880"></a>1.8.2.5. 合并集合</h4></div></div></div>
<pre class="programlisting">
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.union(y)
print(z)
</pre>
<p></p>
<pre class="programlisting">
x = {"a", "b", "c"}
y = {"d", "e", "f"}
z = {"g", "i", "j"}
result = x.union(y, z)
print(result)
</pre>
</div>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="data.dict"></a>1.8.3. Dict 字典</h3></div></div></div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id881"></a>1.8.3.1. 随机选择字典的 key 和 value</h4></div></div></div>
<p>随机字典的 key 和 value</p>
<pre class="screen">
<![CDATA[
names = {1: '张三', 2: '李四', 3: '王五', 4: '赵六', 5: '牛七', 6: '马八'}
print(random.choice(list(names.keys())))
print(random.choice(list(names.values())))
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id882"></a>1.8.3.2. 字典合并</h4></div></div></div>
<pre class="screen">
dict1 = {'name','neo'}
dict2 = {'nickname','netkiller'}
dict1.update(dict2)
print(dict1)
</pre>
<p></p>
<pre class="screen">
{'name', 'neo', 'nickname', 'netkiller'}
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id883"></a>1.8.3.3. 取 Value 最大值</h4></div></div></div>
<pre class="programlisting">
data = {
"Neo": 5,
"Netkiller": 10,
"BG7NYT": 8,
}
ret = max(data, key=lambda x: data[x])
print(ret)
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id884"></a>1.8.3.4. 指定 key 取 value 最大值</h4></div></div></div>
<pre class="programlisting">
data = [
{
"question": "为什么过只加汇摇晃",
"answer": "因为支架是由很多支索小圆轮组成的,所以吊厢过索轮时会有轻微的震动和摇晃,这些都是正常的",
"ratio": 0,
"distance": 41.112388610839844
},
{
"question": "吊厢过之家为什么会摇晃",
"answer": "因为支架是由很多支索小圆轮组成的,所以吊厢过索轮时会有轻微的震动和摇晃,这些都是正常的",
"ratio": 0,
"distance": 42.78510284423828
},
{
"question": "嗦道为啥会摇晃",
"answer": "因为支架是由很多支索小圆轮组成的,所以吊厢过索轮时会有轻微的震动和摇晃,这些都是正常的",
"ratio": 1,
"distance": 44.00849914550781
}
]
ret = max(data, key=lambda dic: dic['ratio'])
print(ret)
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id885"></a>1.8.3.5. 字典求和</h4></div></div></div>
<pre class="programlisting">
count = sum(dict.values())
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id886"></a>1.8.3.6. 对 value 排序后返回 key</h4></div></div></div>
<pre class="programlisting">
data = {
"Neo": 5,
"Netkiller": 10,
"BG7NYT": 8,
}
ret = sorted(data, key=lambda x: data[x])
print(ret)
ret = sorted(data, key=lambda x: data[x],reverse=True)
print(ret)
ret = sorted(data, key=lambda x: data[x],reverse=False)
print(ret)
</pre>
<p>返回结果</p>
<pre class="screen">
['Neo', 'BG7NYT', 'Netkiller']
['Netkiller', 'BG7NYT', 'Neo']
['Neo', 'BG7NYT', 'Netkiller']
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id887"></a>1.8.3.7. 两个 list 合并为 dict</h4></div></div></div>
<p>python header = ['a','b','c'] body=[1,2,3] 转成 dict. {'a':1,
'b': 2, 'c':3}
</p>
<pre class="programlisting">
可以使用 Python 的 zip() 函数将两个列表合并为字典,zip() 会将对应索引的元素配对,然后通过 dict() 转换为字典:
将两个列表转换为字典
原理说明:
zip(header, body) 会将两个列表中对应位置的元素组合成元组,形成类似 [('a', 1), ('b', 2), ('c', 3)] 的可迭代对象。
dict() 函数会将这些元组转换为字典,元组的第一个元素作为键,第二个元素作为值。
注意事项:
如果两个列表长度不一致,zip() 会以较短的列表为准,忽略超出部分的元素。
例如:header = ['a', 'b'],body = [1, 2, 3],结果会是 {'a': 1, 'b': 2}。
header = ['a', 'b', 'c']
body = [1, 2, 3]
# 使用zip()配对后转换为字典
result_dict = dict(zip(header, body))
print(result_dict) # 输出: {'a': 1, 'b': 2, 'c': 3}
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id888"></a>1.8.3.8. 计算 value 的数量</h4></div></div></div>
<pre class="programlisting">
data = {
'产品目标': ['竞品分析'],
'开发目标': ['编码开发', '代码测试'],
'运营目标': ['区域投放']
}
# 计算每个value的数量
count_result = {key: len(value) for key, value in data.items()}
print("每个目标包含的子项数量:")
for key, count in count_result.items():
print(f"{key}:{count}个")
</pre>
</div>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="Iterator"></a>1.8.4. Iterator</h3></div></div></div>
<pre class="programlisting">
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 创建 Iterator 对象
it = iter([1, 2, 3, 4, 5])
# 开始循环
while True:
try:
# 获得下一个值
x = next(it)
print(x)
except StopIteration:
# 遇到StopIteration终止循环
break
</pre>
<p>设置结束标志符</p>
<pre class="programlisting">
#!/usr/bin/python
# -*- coding: UTF-8 -*-
it = iter([1, 2, 5, 4, 3])
while True:
x = next(it, 'a')
print(x)
if x == 'a':
break
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="python.queue"></a>1.8.5. 队列</h3></div></div></div>
<pre class="programlisting">
import queue
q = queue.SimpleQueue()
for n in range(10):
q.put(n)
print("队列数量:", q.qsize())
while not q.empty():
print(q.get())
print("队列状态:", q.empty())
</pre>
<p>先进先出队列,保持队列最大尺寸,超过尺寸自动出队</p>
<pre class="programlisting">
from queue import Queue
q = Queue(maxsize=3)
for i in range(10):
if q.full():
q.get()
q.put(i, block=False)
print(type(q.queue), q.queue)
while not q.empty():
i = q.get(block=False)
print(i)
</pre>
<pre class="programlisting">
from queue import Queue
q = Queue(maxsize=10)
for i in range(20):
if q.full():
q.get()
q.put(i, block=False)
print(type(q.queue), q.queue)
for n in range(5):
if not q.empty():
i = q.get(block=False)
print(i)
</pre>
</div>
</div><script xmlns="" type="text/javascript" id="clustrmaps" src="//cdn.clustrmaps.com/map_v2.js?u=r5HG&d=9mi5r_kkDC8uxG8HuY3p4-2qgeeVypAK9vMD-2P6BYM"></script><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="type.html">上一页</a> </td><td width="20%" align="center"><a accesskey="u" href="index.html">上一级</a></td><td width="40%" align="right"> <a accesskey="n" href="python.serializable.html">下一页</a></td></tr><tr><td width="40%" align="left" valign="top">1.7. 数据类型 </td><td width="20%" align="center"><a accesskey="h" href="../index.html">起始页</a></td><td width="40%" align="right" valign="top"> 1.9. 序列化 </td></tr></table></div><script xmlns="">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-11694057-1', 'auto');
ga('send', 'pageview');
</script><script xmlns="" async="async">
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?93967759a51cda79e49bf4e34d0b0f2c";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script><script xmlns="" async="async">
(function(){
var bp = document.createElement('script');
var curProtocol = window.location.protocol.split(':')[0];
if (curProtocol === 'https') {
bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
}
else {
bp.src = 'http://push.zhanzhang.baidu.com/push.js';
}
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(bp, s);
})();
</script></body></html>