-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.data-types&operators.md
More file actions
878 lines (652 loc) · 25.5 KB
/
Copy path1.data-types&operators.md
File metadata and controls
878 lines (652 loc) · 25.5 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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
Python 中的数据类型和运算符
---
### 概述
- 数据类型:整型、浮点型、布尔型、字符串、列表、元组、集合、字典
- 运算符:算术、赋值、比较、逻辑、成员、恒等运算符
- 内置函数、复合数据结构、类型转换
- 空格和样式指南(详见最后的参考链接)
---
### 变量
- 变量的定义
```Python
students_num = 500
```
说明:students_num 是变量,负责存储 500 的值。该表达式将右侧的项目赋值给左侧的名称,实际上和数学等式有所不同,因为 500 不存储 students_num 的值。
- 变量不同的赋值方式
```Python
# 方式一
x = 3
y = 4
z = 5
# 方式二
a, b, c = 3, 4, 5
```
- 变量命名的注意事项
```Python
1. 只能在变量名称中使用常规字母、数字和下划线。不能包含空格,并且需要以字母或下划线开头。
2. 不能使用保留字或内置标识符,它们在 Python 中具有重要含义。
3. 在 python 中,变量名称的命名方式是全部使用小写字母,并用下划线区分单词, 区分大小写,用小写是规范。
```
### Python 中的保留字
<div align=center>
<img width='550' src="./screenshoot/reserved-words.png" alt="reserved-words" />
</div>
### 整数和浮点数
- 数字值可以用到两种 python 数据类型
```
int - 表示整数值
float - 表示小数或浮点数值
```
- 以通过以下语法创建具有某个数据类型的值
```Python
x = int(4.7) # x is now an integer 4
y = float(4) # y is now a float of 4.0
```
- 使用函数 type 检查数据类型
```Python
print(type(x)) # int
print(type(y)) # float
```
- 其他:因为 0.1 的浮点数(或近似值)实际上比 0.1 稍微大些,当我们将好几个这样的值相加时,可以看出在数学上正确的答案与 Python 生成的答案之间有区别。
```Python
print(.1 + .1 + .1 == .3) # False
```
- 编码规范说明:Python 最佳做法需要follow下面链接给出的PEP8 指南。每行代码应该不超过 80 个字符,虽然在某些使用情况下,99 个字符也可以。
### 整数和浮点数[相关练习]
- 辨别下列哪些是`整型`哪些是`浮点型`
```
1. 有多少人参加了你的钓鱼之旅 **整型**
2. 钓到的鱼的长度(以米计)**浮点型**
3. 在钓鱼之旅中钓到的鱼条数 **整型**
4. 钓到第一条鱼所花费的时间(以小时计)**浮点型**
```
- Python 中除以零的相关错误
```Python
print(5 / 0)
```
会出现如下错误:
```log
Traceback (most recent call last):
File "/*/*/code.py", line 1, in <module>
print(5/0)
ZeroDivisionError: division by zero
```
### 关于异常和语法错误
- 异常:是代码运行时发生的问题
- 语法错误:Python 在运行代码之前检查代码时发现的问题
### 算术运算符
- `+` 加
- `-` 减
- `*` 乘
- `/` 除
- `%` 取余(相除后的余数)
- `**` 取幂(注意 `^` 并不执行该运算,你可能在其他语言中见过这种情形)
- `//` 相除后向下取整到最接近的整数
### 算术运算符[相关练习]
- 在过去三个月的电费是 23 美元、32 美元和 64 美元。这三个月的每月平均电费是多少?
```Python
print((23 + 32 + 64) / 3)
```
- 一个区域是宽 9 块砖,长 7 块砖,另一个区域是宽 5 块砖,长 7 块砖。一包砖有 6 块。 问:(1) 需要多少块砖? (2) 如果购买 17 包砖,每包有 6 块砖。剩下多少块砖?
```Python
# Fill this in with an expression that calculates how many tiles are needed.
print(9*7 + 5*7)
# Fill this in with an expression that calculates how many tiles will be left over.
print(17*6 - (9*7 + 5*7))
```
### 赋值运算符
<div align=center>
<img width='550' src="./screenshoot/equal-sign.png" alt="reserved-words" />
</div>
### 赋值运算符[相关练习]
- 这道练习的注释(以 # 开头的行)提供了创建和修改变量的说明。请在每条注释后面根据说明写一行代码。
[注意] 这段代码使用了科学记数法来定义很大的数字。`4.445e8` 等于 `4.445 * 10 ** 8`,也就是 `444500000.0`。
```Python
# The current volume of a water reservoir (in cubic metres)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic metres)
rainfall = 5e6
# decrease the rainfall variable by 10% to account for runoff
rainfall *= 1-0.1
# add the rainfall variable to the reservoir_volume variable
reservoir_volume += rainfall
# increase reservoir_volume by 5% to account for stormwater that flows
# into the reservoir in the days following the storm
reservoir_volume *= 1+0.05
# decrease reservoir_volume by 5% to account for evaporation
reservoir_volume *= 1-0.05
# subtract 2.5e5 cubic metres from reservoir_volume to account for water
# that's piped to arid regions.
reservoir_volume -= 2.5e5
# print the new value of the reservoir_volume variable
print(reservoir_volume)
```
- 思考下面代码的输出
```Python
# 这是关于山景城人口和人口密度的原始数据。
mv_population = 75000
mv_area = 11.995
mv_density = mv_population/mv_area
print(int(mv_density)) # 6252
```
### 布尔型运算符、比较运算符和逻辑运算符
- 布尔数据类型存储的是值 `True` 或 `False`,通常分别表示为 `1` 或 `0`。
- 通常有 `6` 个比较运算符会获得布尔值:
|符号使用情况|布尔型|运算符
|---|----|-----
| 5 < 3 |False|小于
| 5 > 3 | True | 大于
| 3 <= 3 | True | 小于或等于
| 3 >= 5 | False | 大于或等于
| 3 == 5 | False | 等于
| 3 != 5 | True | 不等于
- 需要熟悉的三个逻辑运算符
|逻辑使用情况|布尔型|运算符
|---|----|-----
| 5 < 3 `and` 5 == 5 | False | `and` - 检查提供的所有语句是否都为 True
| 5 < 3 `or` 5 == 5 | True | `or` - 检查是否至少有一个语句为 True
| `not` 5 < 3 | True | `not` - 翻转布尔值
### 布尔型运算符、比较运算符和逻辑运算符[相关练习]
- 哪个地区人口密度更高?里约还是旧金山?
```python
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
san_francisco_pop_density = sf_population / sf_area
rio_de_janeiro_pop_density = rio_population / rio_area
# Write code that prints True if San Francisco is denser than Rio, and False otherwise
print(san_francisco_pop_density > rio_de_janeiro_pop_density) # False
```
2. 为何 Python 使用 `==` 检查是否相等,而不是 `=`?
* 因为 `=` 用来为变量赋值的
### 字符串
- 在 python 中,字符串的变量类型显示为 `str`。你可以使用双引号 `"` 或单引号 `'` 定义字符串
- 定义字符串
```python
my_string = 'this is a string!'
my_string2 = "this is also a string!!!"
# Also , we can use backslash '/' to escape quotes.
this_string = 'Simon\'s skateboard is in the garage.'
print(this_string)
```
- 字符串的常用操作
```python
first_word = 'Hello'
second_word = 'There'
print(first_word + second_word) # HelloThere
print(first_word + ' ' + second_word) # Hello There
print(first_word * 5) # HelloHelloHelloHelloHello
print(len(first_word)) # 5
print(first_word[0]) # H
print(first_word[1]) # e
```
### 字符串[相关练习]
- 在字符串中正确的使用引号
```python
ford_quote = 'Whether you think you can, or you think you can\'t--you\'re right.'
print(ford_quote) # Whether you think you can, or you think you can't--you're right.
```
- 下面这段代码的输出是什么?
```python
coconut_count = "34"
mango_count = "15"
tropical_fruit_count = coconut_count + mango_count
print(tropical_fruit_count) # 3415 (并且 tropical_fruit_count 是字符串)
```
- 编写服务器日志消息
```python
username = "Kinari"
timestamp = "04:50"
url = "http://petshop.com/pets/mammals/cats"
# TODO: print a log message using the variables above.
# The message should have the same format as this one:
# "Yogesh accessed the site http://petshop.com/pets/reptiles/pythons at 16:20."
print(username + ' accessed the site ' + url + ' at ' + timestamp + '.')
```
- 使用字符串连接和 `len` 函数计算某些电影明星的实际完整姓名的长度
```python
given_name = "William"
middle_names = "Bradley"
family_name = "Pitt"
name_length = len(given_name + ' ' + middle_names + ' ' + family_name)
# Now we check to make sure that the name fits within the driving license character limit
# Nothing you need to do here
driving_license_character_limit = 28
print(name_length <= driving_license_character_limit) # True
```
- 我们刚刚使用函数 `len` 计算出字符串的长度。当我们向其提供整数 `835` 而不是字符串时,函数 `len` 会返回什么?
```
Error
```
### 字符串方法
- python 中的方法和函数相似,但是它针对的是你已经创建的变量。方法特定于存储在特定变量中的数据类型。
<div align=center>
<img width='550' src="./screenshoot/str-method.png" alt="reserved-words" />
</div>
- 每个方法都接受字符串本身作为该方法的第一个参数。但是,它们还可以接收其他参数。我们来看看几个示例的输出。
```python
my_string = "sebastian thrun"
my_string.islower() # True
my_string.count('a') # 2
my_string.find('a') # 3
```
- 可以看出,`count` 和 `find` 方法都接受另一个参数。但是,`islower` 方法不接受参数。如果我们要在变量中存储浮点数、整数或其他类型的数据,可用的方法可能完全不同!
### 字符串方法[相关练习]
- 对浮点型对象调用 `islower` 等方法会发生什么?例如 `13.37.islower()`
* 会出现错误, 方法 `islower` 属于字符串方法,而不是浮点数方法。不同类型的对象具有特定于该类型的方法。例如,浮点数具有 `is_integer` 方法,而字符串没有。
- 练习字符串方法
```python
my_name = "my name is Joh."
cap = my_name.capitalize()
print(cap) # My name is joh.
ew = my_name.endswith('li')
print(ew) # False
ind = my_name.index('is')
print(ind) # 8
```
### 类型和类型转换
- 目前我们已经接触的数据类型
```
1. 整型
2. 浮点型
3. 布尔型
4. 字符串
```
- 使用 `type()` 用来检查你所处理的任何变量的数据类型
```python
print(type(4)) # int
print(type(3.7)) # float
print(type('this')) # str
print(type(True)) # bool
```
### 类型和类型转换[相关练习]
- 你认为以下代码的结果是什么?
```python
"0" + 5
```
将会报错:
```log
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int
```
or
```python
0 + "5"
```
将会报错:
```log
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
```
- 以下对象是什么类型:`"12"`
```
str
```
- 以下对象是什么类型:`12.3`?
```
float
```
- 以下对象是什么类型:`len("my_string")`?
```
int
```
- 以下对象是什么类型:`"hippo" *12`?
```
str
```
- 计算总销量
```python
mon_sales = "121"
tues_sales = "105"
wed_sales = "110"
thurs_sales = "98"
fri_sales = "95"
#TODO: Print a string with this format: This week's total sales: xxx
# You will probably need to write some lines of code before the print statement.
total = int(mon_sales) + int(tues_sales) + int(wed_sales) + int(thurs_sales) + int(fri_sales)
print("This week\'s total sales: " + str(total)) # This week's total sales: 529
```
### 列表和成员运算符
- `列表`可以包含我们到目前为止所学的`任何数据类型`并且`可以混合`到一起。
```python
lst_of_random_things = [1, 3.4, 'a string', True] # 这是一个包含 4 个不同类型元素的列表
print(lst_of_random_things[0]) # 1
```
- 获取上述列表的`第一个`值和`最后一个`值
```python
print(lst_of_random_things[0]) # 1
print(lst_of_random_things[len(lst_of_random_things) - 1]) # True
```
- 此外,你可以使用负数从列表的末尾开始编制索引,其中 `-1` 表示最后一个元素,`-2` 表示倒数第二个元素,等等
```python
print(lst_of_random_things[-1]) # True
print(lst_of_random_things[-2]) # a string
```
- 列表切片的应用: 我们可以使用切片功能从列表中提取多个值。在使用切片功能时,务必注意,`下限`索引包含`在内`,`上限`索引`排除在外`, 最终返回的是一个`新的列表`
正常的用法:
```python
lst_of_random_things = [1, 3.4, 'a string', True]
print(lst_of_random_things[1:2]) # [3.4]
```
从列表的开头开始,也可以省略起始值
```python
lst_of_random_things = [1, 3.4, 'a string', True]
print(lst_of_random_things[:2]) # [1, 3.4]
```
要返回到列表结尾的所有值,可以忽略最后一个元素
```python
lst_of_random_things = [1, 3.4, 'a string', True]
print(lst_of_random_things[1:]) # [3.4, 'a string', True]
```
- 在列表里还是不在列表里?关键字 `in` 和 `not in` 返回一个布尔值, 表示某个元素是否存在于列表中,或者某个字符串是否为另一个字符串的子字符串
```python
print('this' in 'this is a string') # True
print('in' in 'this is a string') # True
print('isa' in 'this is a string') # False
print(5 not in [1, 2, 3, 4, 6]) # True
print(5 in [1, 2, 3, 4, 6]) # False
```
- 列表的可变性和顺序
> 可变性是指对象创建完毕后,我们是否可以更改该对象。如果对象(例如列表或字符串)可以更改,则是可变的。但是,如果无法更改对象以创建全新的对象(例如字符串),则该对象是不可变的。
列表可变性测试:
```python
my_lst = [1, 2, 3, 4, 5]
my_lst[0] = 'one'
print(my_lst) # ['one', 2, 3, 4, 5]
```
下面尝试修改字符串:
```python
greeting = "Hello there"
greeting[0] = 'M'
```
尝试修改字符串,引发如下错误:
```log
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
```
但可以修改字符串对象的地址:
```python
greeting = "Hello there"
greeting = 'Hi there'
print(greeting) # Hi there
```
- 本节注意事项:对于你要使用的每种数据类型,你都需要注意两个事项:可变吗?有序吗?
### 列表和成员运算符[相关练习]
- 请使用列表索引根据整型变量 `month` 判断特定月份有多少天,并将该值存储在整型变量 `num_days` 中
```python
month = 8
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
# use list indexing to determine the number of days in month
num_days = days_in_month[month - 1]
print(num_days)
```
- 请使用列表切片记法从此列表中选择列表中的最后三个元素。提示:切片可以使用负索引!
```python
eclipse_dates = ['June 21, 2001', 'December 4, 2002', 'November 23, 2003',
'March 29, 2006', 'August 1, 2008', 'July 22, 2009',
'July 11, 2010', 'November 13, 2012', 'March 20, 2015',
'March 9, 2016']
# TODO: Modify this line so it prints the last three elements of the list
print(eclipse_dates[-3:])
```
### 列表的常用方法
- 常用方法举例
* `len()` 返回列表中的元素数量。
* `max()` 返回列表中的最大元素。最大元素的判断依据是列表中的对象类型。数字列表中的最大元素是最大的数字。字符串列表中的最大元素是按照字母顺序排序时排在最后一位的元素。因为 `max()` 函数的定义依据是大于比较运算符。如果列表包含不同的无法比较类型的元素,则 `max()` 的结果是 undefined。
* `min()` 返回列表中的最小元素。它是 `max()` 函数的对立面,返回列表中的最小元素。
* `sorted()` 返回一个从最小到最大排序的列表副本,并使原始列表保持不变。
* `join()` 将字符串列表作为参数,并返回一个由列表元素组成并由分隔符字符串分隔的字符串。
* `append()` 实用方法 `append()` 会将元素添加到列表末尾。
- 方法实践举例之`join()`
```python
new_str = "\n".join(["fore", "aft", "starboard", "port"])
print(new_str)
```
输出: 在此示例中,我们使用字符串 "\n" 作为分隔符,以便每个元素之间都有一个换行符。我们还可以在 .join 中使用其他字符串作为分隔符。以下代码使用的是连字符。
```
fore
aft
starboard
port
```
or
```python
name = "-".join(["García", "O'Kelly"])
print(name)
```
输出:
```log
García-O'Kelly
```
- 方法实践举例之`append()`
```python
letters = ['a', 'b', 'c', 'd']
letters.append('z')
print(letters)
```
输出:
```log
['a', 'b', 'c', 'd', 'z']
```
### 列表的常用方法[相关练习]
- 以下代码的输出是什么?
```python
a = [1, 5, 8]
b = [2, 6, 9, 10]
c = [100, 200]
print(max([len(a), len(b), len(c)])) # 4
print(min([len(a), len(b), len(c)])) # 2
```
- 以下代码的输出是什么?
```python
names = ["Carol", "Albert", "Ben", "Donna"]
print(" & ".join(sorted(names))) # Albert & Ben & Carol & Donna
```
- 以下代码的输出是什么?
```python
names = ["Carol", "Albert", "Ben", "Donna"]
names.append("Eugenia")
print(sorted(names)) # ['Albert', 'Ben', 'Carol', 'Donna', 'Eugenia']
```
### 元组 (Tuples)
- 概念解释:元组是另一个实用容器。它是一种不可变有序元素数据类型,并且可以通过索引访问这些对象,通常用来存储相关的信息,示例如下:
```python
location = (13.4125, 103.866667)
print("Latitude:", location[0]) # Latitude: 13.4125
print("Longitude:", location[1]) # Longitude: 103.866667
```
- 元组还可以用来以紧凑的方式为多个变量赋值
```python
dimensions = 52, 40, 100
length, width, height = dimensions # 此处叫元组解包,即:元组为多个变量同时赋值
print("The dimensions are {} x {} x {}".format(length, width, height))
```
- 我们不需要直接使用 `dimensions`,可以将这两行代码简写为一行,一次性为三个变量赋值!
```python
length, width, height = 52, 40, 100
print("The dimensions are {} x {} x {}".format(length, width, height))
```
- 备注:在定义元组时,小括号是可选的,如果小括号并没有对解释代码有影响,程序员经常会忽略小括号。
### 元组[相关练习]
- 以下代码的输出是什么?
```python
tuple_a = 1, 2
tuple_b = (1, 2)
print(tuple_a == tuple_b) # True
print(tuple_a[1]) # 2
```
### 集合
- 概念解释:一个包含唯一元素的`可变`和`无序`的集合数据类型。集合的一个用途是快速删除列表中的重复项。
```python
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set(numbers)
print(unique_nums) # {1, 2, 3, 6}
```
- 支持 `in` 运算符, 使用 `add` 方法将元素添加到集合中,并使用 `pop` 方法删除元素(会随机删除一个元素)
```python
fruit = {"apple", "banana", "orange", "grapefruit"} # define a set
print("watermelon" in fruit) # False
fruit.add("watermelon") # add an element
print(fruit) # {'grapefruit', 'orange', 'watermelon', 'banana', 'apple'}
print(fruit.pop()) # remove a random element: grapefruit
print(fruit) # {'orange', 'watermelon', 'banana', 'apple'}
```
- 你可以对集合执行的其他操作包括可以对数学集合执行的操作。可以对集合轻松地执行 union、intersection 和 difference 等方法,并且与其他容器相比,速度快了很多。
### 集合[相关练习]
- 下面的代码输出是什么?
```python
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
b = set(a)
print(len(a) - len(b)) # 6
```
- 请看看以下代码:
```python
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
b = set(a)
b.add(5)
b.pop()
```
执行这段代码后,数字 `5` 会在集合 `b` 中吗?
回答:`可能在,因为集合的pop是随机删除一个元素的`
### 字典
- 字典是可变数据类型,其中存储的是唯一键到值的映射。
```python
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
```
- 字典的键可以是任何不可变类型,例如整数或元组,而不仅仅是字符串。甚至每个键都不一定要是相同的类型!
```python
print(elements["helium"]) # 2
```
- 我们可以使用方括号并在括号里放入键,查询字典中的值或向字典中插入新值
```python
elements["lithium"] = 3
```
- 使用关键字 `in` 检查值是否在字典中。字典有一个也很有用的相关方法,叫做 `get`。`get` 会在字典中查询值,但是和方括号不同,如果没有找到键,`get` 会返回 `None`(或者你所选的默认值)
```python
print("carbon" in elements) # True
print(elements.get("dilithium")) # None
```
- 如果你预计查询有时候会失败,`get` 可能比`普通的方括号`查询更合适,因为错误可能会使程序崩溃。
### 恒等运算符
- 概念解释
| 关键字 | 运算符
|---|----
| is | 检查两边是否恒等
| is not | 检查两边是否不恒等
- 你可以使用运算符 is 检查某个键是否返回了 None。或者使用 is not 检查是否没有返回 None。
```python
n = elements.get("dilithium")
print(n is None) # True
print(n is not None) # False
```
### 字典和恒等运算符[相关练习]
- 定义一个叫做 population 的字典
```python
# Key | Value
# Shanghai | 17.8
# Istanbul | 13.3
# Karachi | 13.0
# Mumbai | 12.5
population = {
"Shanghai":17.8,
"Istanbul":13.3,
"Karachi":13.0,
"Mumbai":12.5
}
print(population["Mumbaix"]) # 12.5
```
- 以下哪些项可以用作字典的键?(请选中所有适用项。) Hint: 字典的键必须是不可变的,即所属的类型必须不可变。
```python
# 可用
str, int, float, tuples, bool
# 不可用
list, set, dictionaries
```
- 如果我们查找不在字典中的值,会发生什么?
发生 `KeyError`
- 字典有一个也很有用的相关方法,叫做 get。get 会在字典中查询值,但是和方括号不同,如果没有找到键,get 会返回 None(或者你所选的默认值)
正确的使用方式:
```python
elements.get('dilithium') # None
```
错误的使用方式:
```python
elements['dilithium'] # KeyError: 'dilithium'
```
使用get并添加默认值, 当键没找到时,`get` 会返回该值。
```python
elements.get('kryptonite', 'There\'s no such element!') # "There's no such element!"
```
### 检查是否相等与恒等:== 与 is
- 以下代码的输出是什么?
```python
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a == b) # True
print(a is b) # True
print(a == c) # True
print(a is c) # False
```
### 复合数据结构
- 我们可以在其他容器中包含容器,以创建复合数据结构
```python
# 定义一个复合数据结构
elements = {"hydrogen": {"number": 1,
"weight": 1.00794,
"symbol": "H"},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"}}
# 访问复合数据结构中的值
helium = elements["helium"] # get the helium dictionary
hydrogen_weight = elements["hydrogen"]["weight"] # get hydrogen's weight
```
### 复合数据结构[相关练习]
- 向 elements 字典中的每个字典添加另一个条目 'is_noble_gas。插入新条目后,你应该能够执行以下查询:
```python
print(elements['hydrogen']['is_noble_gas']) # False
print(elements['helium']['is_noble_gas']) # True
```
代码如下:
```python
elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},
'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
elements['hydrogen']['is_noble_gas'] = False
elements['helium']['is_noble_gas'] = True
print(elements['hydrogen']['is_noble_gas'])
print(elements['helium']['is_noble_gas'])
```
- 具有哪些属性可以使用 Python 中的 `列表`来表示?
```log
1. 项目的索引始终以 0 开始
2. 可排序
3. 使用 .append 添加项目
```
- 具有哪些属性可以使用 Python 中的 `集合`来表示
```log
1. 项目的出现顺序可能不一致
2. 可变(你可以更改它)
3. 使用 .add 添加项目
```
- 具有哪些属性可以使用 Python 中的 `字典`来表示
```log
1. 每项都包含两部分
2. 项目的出现顺序可能不一致
3. 可以嵌套
```
### 参考链接
- https://en.wikipedia.org/wiki/History_of_Python
- https://wiki.python.org/moin/BitwiseOperators
- https://en.wikipedia.org/wiki/Operation_(mathematics)%E3%80%82
- https://pentangle.net/python/handbook/node52.html
- https://pentangle.net/python/handbook/node20.html
- https://en.wikipedia.org/wiki/Scientific_notation
- https://docs.python.org/3/tutorial/floatingpoint.html
- https://www.python.org/dev/peps/pep-0008/
- https://atom.io/packages/linter-python-pep8
- https://softwareengineering.stackexchange.com/questions/148677/why-is-80-characters-the-standard-limit-for-code-width
- https://docs.python.org/3/tutorial/errors.html
- https://docs.python.org/3/library/stdtypes.html#string-methods