□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(Omi Chiba)

Pythonは動的型付け言語です。つまり、変数に特定の型はなく、それゆえ宣言する必要がありません。一方で、値は特定の型を持っています。以下のようにして、変数に対して、そこに格納された値の型について問い合わせることができます。

Python is a dynamically typed language, meaning that variables do not have a type and therefore do not have to be declared. Values, on the other hand, do have a type. You can query a variable for the type of value it contains:

1.

2.

3.

4.

5.

6.

7.

8.

9.

>>> a = 3

>>> print type(a)

<type 'int'>

>>> a = 3.14

>>> print type(a)

<type 'float'>

>>> a = 'hello python'

>>> print type(a)

<type 'str'>

Pythonはまた、最初からリストや辞書などのデータ構造を内包しています。

Python also includes, natively, data structures such as lists and dictionaries.

str

Pythonは、ASCII文字列とUnicode文字列の2つの異なる型の文字列の使用をサポートしています。ASCII文字列は'...'、"..."、'''..'''、"""..."""で区切られたものです。トリプルクォートは、複数行の文字列を区切ります。Unicode文字列はuで始まり、Unicode文字列がその後に続きます。次のようにエンコーディングを選択することで、Unicode文字列をASCII文字列に変換することができます。

Python supports the use of two different types of strings: ASCII strings and Unicode strings. ASCII strings are delimited by '...', "..." or by "'.."' or """...""". Triple quotes delimit multiline strings. Unicode strings start with a u followed by the string containing Unicode characters. A Unicode string can be converted into an ASCII string by choosing an encoding for example:

1.

2.

3.

>>> a = 'this is an ASCII string'

>>> b = u'This is a Unicode string'

>>> a = b.encode('utf8')

上記のコマンド実行により、aの結果はUTF8でエンコードされた文字列を格納するASCII文字列になります。web2pyは意図的に、UTF8でエンコードされた文字列を内部で使用します。

After executing these three commands, the resulting a is an ASCII string storing UTF8 encoded characters. By design, web2py uses UTF8 encoded strings internally.

また、さまざまな方法で、変数を文字列で記述することが可能です:

It is also possible to write variables into strings in various ways:

1.

2.

3.

4.

5.

6.

>>> print 'number is ' + str(3)

number is 3

>>> print 'number is %s' % (3)

number is 3

>>> print 'number is %(number)s' % dict(number=3)

number is 3

最後の表記はより明示的でエラーが起きにくいので、推奨される書き方です。

The last notation is more explicit and less error prone, and is to be preferred.

多くのPythonオブジェクトは、たとえば数字は、strまたはreprを用いて文字列にシリアライズすることができます。これら2つのコマンドは非常に似ていますが、若干異なる出力結果を生成します。例:

Many Python objects, for example numbers, can be serialized into strings using str or repr. These two commands are very similar but produce slightly different output. For example:

1.

2.

3.

4.

>>> for i in [3, 'hello']:

print str(i), repr(i)

3 3

hello 'hello'

ユーザー定義クラスにおいて、strやreprは__str__と__repr__という特別な演算子を用いて定義/再定義できます。これらは後ほど簡単に説明します。より詳細についてはPython公式ドキュメントを参照してください。なお、reprは常に​​デフォルトの値を持っています 。

For user-defined classes, str and repr can be defined/redefined using the special operators__str__ and __repr__. These are briefly described later on; for more, refer to the official Python documentation39 . repr always has a default value.

Python文字列のもう1つの重要な特徴は、リストのように反復可能なオブジェクトであるという点です。

Another important characteristic of a Python string is that, like a list, it is an iterable object.

1.

2.

3.

4.

5.

6.

7.

>>> for i in 'hello':

print i

h

e

l

l

o

list

Pythonリストの主要なメソッドは追加(append)、挿入(insert)、削除(delete)です:

The main methods of a Python list are append, insert, and delete:

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

>>> a = [1, 2, 3]

>>> print type(a)

<type 'list'>

>>> a.append(8)

>>> a.insert(2, 7)

>>> del a[0]

>>> print a

[2, 7, 3, 8]

>>> print len(a)

4

リストは次のようにスライスできます:

Lists can be sliced:

1.

2.

3.

4.

5.

6.

>>> print a[:3]

[2, 7, 3]

>>> print a[1:]

[7, 3, 8]

>>> print a[-2:]

[3, 8]

連結することも可能です:

and concatenated:

1.

2.

3.

4.

>>> a = [2, 3]

>>> b = [5, 6]

>>> print a + b

[2, 3, 5, 6]

リストは反復可能です。つまり、それをループで回すことができます:

A list is iterable; you can loop over it:

1.

2.

3.

4.

5.

6.

>>> a = [1, 2, 3]

>>> for i in a:

print i

1

2

3

リストの要素は同じ型にする必要はありません。任意のPythonオブジェクトをとることができます。

The elements of a list do not have to be of the same type; they can be any type of Python object.

リスト内包表記を利用することができるとても一般的な状況があります。 以下のコードを考えてください。

There is a very common situation for which a list comprehension can be used. Consider the following code:

1.

2.

3.

4.

5.

6.

7.

>>> a = [1,2,3,4,5]

>>> b = []

>>> for x in a:

if x % 2 == 0:

b.append(x * 3)

>>> b

[6, 12]

上記のコードは明らかに、リストの項目を処理し、入力リストの一部を選択し修正し、新たなリストを作成しています。このコードは以下のようにして完全に書き換えることができます。

This code clearly processes a list of items, selects and modifies a subset of the input list, and creates a new result list, and this code can be entirely replaced with the following list comprehension:

1.

2.

3.

4.

>>> a = [1,2,3,4,5]

>>> b = [x * 3 for x in a if x % 2 == 0]

>>> b

[6, 12]

tuple

タプルはリストに似ていますが、そのサイズと要素は、リストは変更可能なのに対し、タプルは変更不可能です。タプルの要素がオブジェクトである場合、オブジェクトの属性は変更可能です。タプルは丸括弧で区切られます。

A tuple is like a list, but its size and elements are immutable, while in a list they are mutable. If a tuple element is an object, the object attributes are mutable. A tuple is delimited by round brackets.

1.

>>> a = (1, 2, 3)

したがって、以下のコードはリストに対しては動作しますが、

So while this works for a list:

1.

2.

3.

4.

>>> a = [1, 2, 3]

>>> a[1] = 5

>>> print a

[1, 5, 3]

タプルに対しては、要素の割り当てが機能しません。

the element assignment does not work for a tuple:

1.

2.

3.

4.

5.

6.

7.

>>> a = (1, 2, 3)

>>> print a[1]

2

>>> a[1] = 5

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

タプルはリストと同様に反復可能なオブジェクトです。注意として、単一の要素でタプルを構成する際は、以下のように末尾にコンマをつけなければいけません:

A tuple, like a list, is an iterable object. Notice that a tuple consisting of a single element must include a trailing comma, as shown below:

1.

2.

3.

4.

5.

6.

>>> a = (1)

>>> print type(a)

<type 'int'>

>>> a = (1,)

>>> print type(a)

<type 'tuple'>

タプルはその不変性と括弧の利用が省略可能であることから、オブジェクトを効率的に格納するのにとても便利です。

Tuples are very useful for efficient packing of objects because of their immutability, and the brackets are often optional:

1.

2.

3.

4.

5.

6.

>>> a = 2, 3, 'hello'

>>> x, y, z = a

>>> print x

2

>>> print z

hello

dict

Pythonのdictionary(辞書)はキーオブジェクトを値オブジェクトにマッピングするハッシュテーブルです。例:

A Python dict-ionary is a hash table that maps a key object to a value object. For example:

1.

2.

3.

4.

5.

6.

7.

8.

9.

>>> a = {'k':'v', 'k2':3}

>>> a['k']

v

>>> a['k2']

3

>>> a.has_key('k')

True

>>> a.has_key('v')

False

キーは任意の型のハッシュ可能な型(int、string、他、__hash__メソッド実装したクラスのオブジェクト)をとることができます。値は任意の型を使用できます。同じ辞書内の異なるキーと値は、同じ型にする必要はありません。 キーが英数字の場合は、辞書は次のような代替の構文を用いて宣言することができます:

Keys can be of any hashable type (int, string, or any object whose class implements the__hash__ method). Values can be of any type. Different keys and values in the same dictionary do not have to be of the same type. If the keys are alphanumeric characters, a dictionary can also be declared with the alternative syntax:

1.

2.

3.

4.

5.

>>> a = dict(k='v', h2=3)

>>> a['k']

v

>>> print a

{'k':'v', 'h2':3}

便利なメソッドは、keys、values、items です。

Useful methods are has_key, keys, values and items:

1.

2.

3.

4.

5.

6.

7.

>>> a = dict(k='v', k2='3)

>>> print a.keys()

['k', 'k2']

>>> print a.values()

['v', 3]

>>> print a.items()

[('k', 'v'), ('k2', 3)]

itemsメソッドはタプルのリストを生成し、各タプルはキーとそれに対応付けられた値を格納しています。

The items method produces a list of tuples, each containing a key and its associated value.

辞書の要素とリストの要素は、delコマンドで削除することができます。

Dictionary elements and list elements can be deleted with the command del:

1.

2.

3.

4.

5.

6.

7.

8.

>>> a = [1, 2, 3]

>>> del a[1]

>>> print a

[1, 3]

>>> a = dict(k='v', h2=3)

>>> del a['h2']

>>> print a

{'k':'v'}

内部的には、Pythonは、hash演算子でオブジェクトを整数に変換し、その整数によってどこに値を格納するかを決めています。

Internally, Python uses the hash operator to convert objects into integers, and uses that integer to determine where to store the value.

1.

2.

>>> hash("hello world")

-1500746465