Skip to content

Commit 487314e

Browse files
committed
add translated for 'Lists vs. Tuples'
1 parent b4e85cf commit 487314e

8 files changed

Lines changed: 139 additions & 726 deletions

Others/Lists和Tuples大对决.md

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
原文:[Lists vs. Tuples](http://nedbatchelder.com/blog/201608/lists_vs_tuples.html "Link to this post" )
2+
3+
---
4+
5+
常见的Python初学者问题:列表和元组之间有何区别?
6+
7+
答案是,有两个不同的差异,以及两者之复杂的相互作用。这就是技术差异和文化差异。
8+
9+
首先:它们有相同之处:列表和元组都是容器,即对象序列:
10+
11+
```python
12+
>>> my_list = [123]
13+
>>> type(my_list)
14+
<class 'list'>
15+
>>> my_tuple = (123)
16+
>>> type(my_tuple)
17+
<class 'tuple'>
18+
```
19+
20+
它们任意一个的元素可以是任意类型,甚至在一个单一序列中。它们都维护元素的顺序(不像集合和字典那样)。
21+
22+
现在是不同之处。列表和元组之间的技术差异是,列表示可变的(可以被改变),而元组是不可变的(不可以被改变)。这是Python语言对它们的唯一区分:
23+
24+
```python
25+
>>> my_list[1= "two"
26+
>>> my_list
27+
[1'two'3]
28+
>>> my_tuple[1= "two"
29+
Traceback (most recent call last):
30+
  File "<stdin>", line 1in <module>
31+
TypeError'tuple' object does not support item assignment
32+
```
33+
34+
这就是列表和元组之间的唯一技术差异,虽然它体现在几个方面。例如,列表有一个.append()方法,用以添加更多元素到列表中,而元组并没有:
35+
36+
```python
37+
>>> my_list.append("four")
38+
>>> my_list
39+
[1'two'3'four']
40+
>>> my_tuple.append("four")
41+
Traceback (most recent call last):
42+
  File "<stdin>", line 1in <module>
43+
AttributeError'tuple' object has no attribute 'append'
44+
```
45+
46+
元组并不需要.append()方法,因为你不可以修改元组。
47+
48+
文化差异是关于列表和元组的实际使用的:当你有一个未知长度的同质序列时使用列表;当你预先知道元素个数的时候使用元组,因为元素的位置语义上是显著的。
49+
50+
例如,假设你有一个函数,它查找目录下以*.py结尾的文件。它应该返回一个列表,因为你并不知道会找到多少个文件,而它们都具有相同的语义:只是你找到的另一个文件。
51+
52+
```python
53+
>>> find_files("*.py")
54+
["control.py""config.py""cmdline.py""backward.py"]
55+
```
56+
57+
另外,假设你需要存储五个值来表示气象观测站的位置:id, city, state, latitude和longitude。那么较之列表,元组更适合:
58+
59+
```python
60+
>>> denver = (44"Denver""CO"40105)
61+
>>> denver[1]
62+
'Denver'
63+
```
64+
65+
(目前,不要讨论使用类来替代)这里,第一个元素是id,第二个元素是city,以此类推。位置决定了意思。
66+
67+
将文化差异加之于C语言上,列表像数组,元组像结构。
68+
69+
Python有一个namedtuple工具,它可以让意思更加明确:
70+
71+
```python
72+
>>> from collections import namedtuple
73+
>>> Station = namedtuple("Station""id, city, state, lat, long")
74+
>>> denver = Station(44"Denver""CO"40105)
75+
>>> denver
76+
Station(id=44city='Denver'state='CO'lat=40long=105)
77+
>>> denver.city
78+
'Denver'
79+
>>> denver[1]
80+
'Denver'
81+
```
82+
83+
元组和列表之间的文化差异一个聪明的总结是:元组是没有名字的namedtuple。
84+
85+
技术差异和文化差异是一个不稳定的联盟,因为有时它们相左。为什么同源序列应该可变,而异源序列不是?例如,因为namedtuple是一个元组,它是不可变的,所以我不可以修改我的气象站:
86+
87+
```python
88+
 denver.lat = 39.7392
89+
Traceback (most recent call last):
90+
  File "<stdin>", line 1in <module>
91+
AttributeError: can't set attribute
92+
```
93+
94+
有时,技术方面的考虑覆盖了文化因素。你不能把一个列表当做一个字典键,因为只有不可变值才能够被哈希,所以只有不可变值才能作为键。要把一个列表当成键,你可以将其转换成元组:
95+
96+
```python
97+
 d = {}
98+
>>> nums = [123]
99+
>>> d[nums] = "hello"
100+
Traceback (most recent call last):
101+
  File "<stdin>", line 1in <module>
102+
TypeError: unhashable type'list'
103+
>>> d[tuple(nums)] = "hello"
104+
>>> d
105+
{(123): 'hello'}
106+
```
107+
108+
另一个技术和文化的冲突是:Python自身在使用列表更有意义的情况下使用了元组。当你使用*args定义一个函数时,args作为元组传递,即使据Python所知,值的位置并不重要。你可能会说,它是元组,因为你不可以改变你所传递的值,但这只是较之文化,更重视了技术差异。
109+
110+
我知道,我知道,在*args中,位置可能是重要的,因为它们是位置参数。但在一个接受*args,然后将其传递给另一个函数的函数中,它只是一个参数序列,和另一个没什么不同,而它们的数量在调用之间可以不同。
111+
112+
这里,Python使用元组,是因为较之列表,它们的空间效率会多一点。列表是过度分配的,以便让附加更快些。这说明Python务实的一面:因地制宜使用数据结构,而不是纠结于*args的列表/元组语义。
113+
114+
在大多数情况下,你应该基于文化差异选择是使用列表还是元组。想想你的数据的含义。如果基于你的程序在现实世界中遇到的,它会有不同的长度,那么可能要使用列表。如果你知道在你写代码的时候,第三个元素意味着什么,那么可能要使用元组。
115+
116+
另一方面,函数式编程强调不可变数据结构,作为一种避免难以推理代码这一副作用的方式。如果你是一个函数式编程粉,那么你可能会因为不可变性喜欢元组。
117+
118+
所以:你应该使用元组还是列表呢?答案是:它并不总是一个简单的答案。

Others/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,6 @@
118118

119119
- [Requests vs. urllib:它解决了什么问题?](./Requests vs. urllib:它解决了什么问题?.md)
120120

121+
- [Lists和Tuples大对决](./Lists和Tuples大对决.md)
122+
123+
常见的Python初学者问题:列表和元组之间有何区别?答案是,有两个不同的差异,以及两者之复杂的相互作用。这就是技术差异和文化差异。

Python Weekly/Python Weekly Issue 258.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@
2525

2626
这篇文章重温Tensorflow上的RNNs的使用最佳实践,特别是在官网上没有得到很好记录的特性。
2727

28-
[Lists和Tuples大对决](http://nedbatchelder.com/blog/201608/lists_vs_tuples.html)
28+
[Lists和Tuples大对决](http://nedbatchelder.com/blog/201608/lists_vs_tuples.html) | [中文版](../Others/Lists和Tuples大对决.md)
2929

30-
常见的Python初学者问题:列表和元组之间有何区别?答案是,有两个不同的差异,以及两者之复杂的相互作用。还有就是技术差异和文化差异
30+
常见的Python初学者问题:列表和元组之间有何区别?答案是,有两个不同的差异,以及两者之复杂的相互作用。这就是技术差异和文化差异
3131

3232
[Podcast.__init__ 第71集 - 和Radim Řehůřek聊聊Gensim](https://podcastinit.com/radim-rehurek-gensim.html)
3333

raw/Better Python Object Serialization.md

Lines changed: 10 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,6 @@
1-
# [Hynek Schlawack](https://hynek.me/)
1+
原文:[Better Python Object Serialization](https://hynek.me/articles/serialization/)
22

3-
## Pythonista, Gopher, C hacker, JavaScript dabbler, and speaker from
4-
Berlin/Germany.
5-
6-
* [About Me](https://hynek.me/about/)
7-
* [Articles](https://hynek.me/articles)
8-
* [Talks](https://hynek.me/talks/)
9-
10-
# Better Python Object Serialization
11-
12-
22 August 2016
3+
---
134

145
The Python standard library is full of underappreciated gems. One of them
156
allows for simple and elegant function dispatching based on argument types.
@@ -18,11 +9,11 @@ JSON in web APIs and structured logs.
189

1910
Who hasn’t seen it:
2011

21-
[code]
12+
```python
2213

2314
TypeError: datetime.datetime(...) is not JSON serializable
2415

25-
[/code]
16+
```
2617

2718
While this shouldn’t be a big deal, it is. The `json` module – that inherited
2819
its API from `simplejson` – offers two ways to serialize objects:
@@ -40,7 +31,7 @@ support for new types is not provided for. Your single `default()` fallback
4031
has to know about all custom types you want to serialize. Which means you
4132
either write functions like:
4233

43-
[code]
34+
```python
4435

4536
def to_serializable(val):
4637
if isinstance(val, datetime):
@@ -56,7 +47,7 @@ either write functions like:
5647
}
5748
return str(val)
5849

59-
[/code]
50+
```
6051

6152
Which is painful since you have to add serialization for all objects in one
6253
place2.
@@ -99,7 +90,7 @@ legacy Python versions).
9990
Put simply, you define a default function and then register additional
10091
versions of that functions depending on the type of the first argument:
10192

102-
[code]
93+
```python
10394

10495
from datetime import datetime
10596
from functools import singledispatch
@@ -114,18 +105,18 @@ versions of that functions depending on the type of the first argument:
114105
"""Used if *val* is an instance of datetime."""
115106
return val.isoformat() + "Z"
116107

117-
[/code]
108+
```
118109

119110
Now you can call `to_serializable()` on `datetime` instances too and single
120111
dispatch will pick the correct function:
121112

122-
[code]
113+
```python
123114

124115
>>> json.dumps({"msg": "hi", "ts": datetime.now()},
125116
... default=to_serializable)
126117
'{"ts": "2016-08-20T13:08:59.153864Z", "msg": "hi"}'
127118

128-
[/code]
119+
```
129120

130121
This gives you the power to put your serializers wherever you want: along with
131122
the classes, in a separate module, or along with JSON-related code? _You_
@@ -154,27 +145,3 @@ P.S. Of course there’s also a `*multiple*dispatch` on
154145
2. Although as you can see it’s manageable with `attrs`; maybe [you should use `attrs`](https://glyph.twistedmatrix.com/2016/08/attrs.html)! ↩︎
155146
3. Unfortunately the API Pyramid uses is currently [undocumented](https://github.com/zopefoundation/zope.interface/issues/41) after being transplanted from [`zope.component`](https://docs.zope.org/zope.component/). ↩︎
156147
4. I’ve been told the original incentive for adding single dispatch to the standard library was a more elegant reimplementation of [`pprint`](https://docs.python.org/3.5/library/pprint.html) (that never happened). ↩︎
157-
158-
__
159-
160-
[ __ Twitter ](http://twitter.com/share?text=Better%20Python%20Object%20Serial
161-
ization&url=https%3a%2f%2fhynek.me%2farticles%2fserialization%2f "Share on
162-
Twitter" ) [ __ Facebook ](https://www.facebook.com/sharer/sharer.php?u=https%
163-
3a%2f%2fhynek.me%2farticles%2fserialization%2f "Share on Facebook" ) [ __
164-
Google+ ](https://plus.google.com/share?url=https%3a%2f%2fhynek.me%2farticles%
165-
2fserialization%2f "Share on Google+" )
166-
167-
#### Hynek Schlawack
168-
169-
In ♥︎ with Python &amp; networks. Occasionally cheating with Go. OSS
170-
mercenary, blogger, speaker, PSF fellow, coder of mayhem.
171-
172-
__ Berlin/Germany
173-
174-
[__ Twitter](https://twitter.com/hynek "Twitter" ) [__
175-
GitHub](https://github.com/hynek "GitHub" ) [__
176-
RSS](https://hynek.me/index.xml "RSS" ) (C) 2016 Hynek Schlawack
177-
All Rights Reserved • [Impressum](https://hynek.me/imprint/)
178-
179-
![](https://stats.ox.cx/piwik.php?idsite=2)
180-

raw/Handy Python Libraries for Formatting and Cleaning Data.md

Lines changed: 2 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,6 @@
1-
[Home](https://blog.modeanalytics.com/)
2-
[Product](https://about.modeanalytics.com/product/) [Data
3-
Sources](https://about.modeanalytics.com/data-sources/)
4-
[Customers](https://about.modeanalytics.com/customers/)
5-
[Company](https://about.modeanalytics.com/company/)
6-
[Jobs](https://about.modeanalytics.com/jobs/)
7-
[Resources](https://about.modeanalytics.com/resources/) [SQL
8-
School](http://sqlschool.modeanalytics.com)
9-
[Playbook](https://about.modeanalytics.com/playbook/) [Sign
10-
In](https://modeanalytics.com/signin)
1+
原文:[Handy Python Libraries for Formatting and Cleaning Data](https://blog.modeanalytics.com/python-data-cleaning-libraries/)
112

12-
[
13-
14-
](javascript://)
15-
16-
[ ![](https://about.modeanalytics.com/about/img/mode-logo.png)
17-
](https://modeanalytics.com)
18-
19-
[Product](https://about.modeanalytics.com/product/)
20-
[Pricing](https://about.modeanalytics.com/pricing/)
21-
[Community](https://community.modeanalytics.com/)
22-
23-
[ More ![](https://blog.modeanalytics.com/images/triangle.png)
24-
](javascript://)
25-
26-
[Data Sources](https://about.modeanalytics.com/data-sources/)
27-
[Customers](https://about.modeanalytics.com/customers/)
28-
[Company](https://about.modeanalytics.com/company/)
29-
[Jobs](https://about.modeanalytics.com/jobs/)
30-
[Blog](https://blog.modeanalytics.com) [Help](http://help.modeanalytics.com)
31-
32-
[Sign Up](http://modeanalytics.com/signup) [Sign
33-
In](http://modeanalytics.com/signin)
34-
35-
[Mode Blog](https://blog.modeanalytics.com/)
36-
37-
# [Handy Python Libraries for Formatting and Cleaning
38-
Data](https://blog.modeanalytics.com/python-data-cleaning-libraries/)
39-
40-
August 23, 2016 | [Melissa Bierly](http://www.twitter.com/melissa_bierly) --
41-
Content Marketing at Mode
3+
---
424

435
The real world is messy, and so too is its data. So messy, that a [recent
446
survey](http://visit.crowdflower.com/data-science-report.html) reported data
@@ -179,73 +141,3 @@ Here are a couple of our favorite reads on munging/wrangling/cleansing data.
179141
* [Cohort Analysis That Helps You Look Ahead](https://blog.modeanalytics.com/cohort-analysis-helps-look-ahead/?utm_medium=recommended&utm_source=blog&utm_content=data_cleaning)
180142
* [10 Useful Python Data Visualization Libraries for Any Discipline](https://blog.modeanalytics.com/python-data-visualization-libraries/?utm_medium=recommended&utm_source=blog&utm_content=data_cleaning)
181143
* [Thinking in SQL vs Thinking in Python](https://blog.modeanalytics.com/learning-python-sql/?utm_medium=recommended&utm_source=blog&utm_content=data_cleaning)
182-
183-
Category: [Community](https://blog.modeanalytics.com/archive/community)
184-
185-
## Keep your finger on the pulse of analytics.
186-
187-
Each week we publish a roundup of the best analytics and data science content
188-
we can find. Sign up here:
189-
190-
Thanks! Keep an eye on your email for the next issue of the Analytics
191-
Dispatch!
192-
193-
Please enable JavaScript to view the [comments powered by
194-
Disqus.](https://disqus.com/?ref_noscript)
195-
196-
### Next Article
197-
198-
## [Analytics Dispatch 037: End the language
199-
war](https://blog.modeanalytics.com/analytics-dispatch-037/)
200-
201-
![](https://about.modeanalytics.com/about/img/mode-logo.png)
202-
203-
Product
204-
205-
[Overview](https://about.modeanalytics.com/product/)
206-
[SQL](https://about.modeanalytics.com/online-sql-editor/)
207-
[Python](https://about.modeanalytics.com/python/)
208-
[Reporting](https://about.modeanalytics.com/reporting/)
209-
[Pricing](https://about.modeanalytics.com/pricing/)
210-
[Customers](https://about.modeanalytics.com/customers/) [Data
211-
Sources](https://about.modeanalytics.com/data-sources/)
212-
[Security](https://about.modeanalytics.com/security/)
213-
214-
Resources
215-
216-
[Community](https://community.modeanalytics.com) [Learn
217-
SQL](https://community.modeanalytics.com/sql) [Learn
218-
Python](https://community.modeanalytics.com/python) [Open Source
219-
SQL](https://about.modeanalytics.com/playbook/) [Retention
220-
Analytics](https://about.modeanalytics.com/improving-retention-rates/) [CRM
221-
Analytics](https://about.modeanalytics.com/sales-analytics/) [Help +
222-
Support](http://help.modeanalytics.com)
223-
224-
Company
225-
226-
[About](https://about.modeanalytics.com/company/)
227-
[Careers](https://about.modeanalytics.com/jobs/)
228-
[Press](https://about.modeanalytics.com/press/)
229-
[Blog](http://blog.modeanalytics.com)
230-
231-
Contact Us
232-
233-
415-689-7436
234-
235-
208 Utah St. Suite 300
236-
237-
San Francisco CA 94103
238-
239-
[ ![Facebook](https://blog.modeanalytics.com/images/social-logos/facebook.png)
240-
](https://www.facebook.com/ModeAnalytics) [
241-
![Twitter](https://blog.modeanalytics.com/images/social-logos/twitter.png)
242-
](https://twitter.com/modeanalytics) [
243-
![LinkedIn](https://blog.modeanalytics.com/images/social-logos/linkedin.png)
244-
](https://www.linkedin.com/company/mode-analytics) [
245-
![GitHub](https://blog.modeanalytics.com/images/social-logos/github.png)
246-
](https://github.com/mode)
247-
248-
(C) Mode Analytics, Inc. 2015 [terms of
249-
service](https://about.modeanalytics.com/tos/) [privacy
250-
policy](https://about.modeanalytics.com/privacy/)
251-

0 commit comments

Comments
 (0)