3. Базовые типы данных в Python.

Целые числа

# int
print 42
print int()
print int("42")
print int("0x2A", 16)
print int("0b101010", 2)
print type(3 / 2), 3 / 2
42
0
42
42
42
<type 'int'> 1
# long
print type(11)
print type(long(11)), long(11)
print type(19829237482379273847293478921374987234), 19829237482379273847293478921374987234
print type(10 ** 100), 10 ** 100
print type(2 ** 62), 2 ** 62
print type(2 ** 62 + 2 ** 62), 2 ** 62 + 2 ** 62
<type 'int'>
<type 'long'> 11
<type 'long'> 19829237482379273847293478921374987234
<type 'long'> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
<type 'int'> 4611686018427387904
<type 'long'> 9223372036854775808

Действительные числа

# float
print .0
print float()
print 1e-10
print 1 * 1.0
print type(3.0 / 2), 3.0 / 2
0.0
0.0
1e-10
1.0
<type 'float'> 1.5

Комплексные числа

# complex
print complex()
print type(1 + 0j), 1 + 0j
print type(1 + 0j + 3), 1 + 0j + 3
print (2 + 3j) * (4 + 1j)
print (1 + 10j) * (1 - 10j)
0j
<type 'complex'> (1+0j)
<type 'complex'> (4+0j)
(5+14j)
(101+0j)

Логический тип

# bool
print bool()
print type(True), True
print type(False), False
False
<type 'bool'> True
<type 'bool'> False

Тип для пустоты

# None
print type(None), None
a = None
print a is None # comparison of singletons
<type 'NoneType'> None
True

Коллекции

Последовательности

Примеры встроенных типов:

Свойства:

Список (list) - динамический массив


Код, много кода
# literal
print []
print [1]
print [1, 2, 3, "four", [5, 6]]

[]
[1]
[1, 2, 3, 'four', [5, 6]]
# range function
print range(10)
print range(5, 10)
print range(1, 10, 2)
print range(10, 1, -1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
[10, 9, 8, 7, 6, 5, 4, 3, 2]
# length
arr = range(10)
print arr
print len(arr)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
10
# indexing
arr = range(10)
print arr
print arr[0]
print arr[3]
print arr[-1]
print arr[-3]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
3
9
7
# slicing part one
arr = range(10)
print arr
print arr[:5]
print arr[5:]
print arr[5:8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[5, 6, 7]
# slicing part two
arr = range(10)
print arr
arr[5:8] = ["ha", "ha", "ha"]
print arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 'ha', 'ha', 'ha', 8, 9]
# slicing part three
arr = range(10)
print arr
print arr[3:9]
print arr[3:9:2]
print arr[::-1]
arr[3:7] = arr[6:2:-1]
print arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8]
[3, 5, 7]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[0, 1, 2, 6, 5, 4, 3, 7, 8, 9]
# iteration
for elem in [1, 2, "three", []]:
    print elem
1
2
three
[]
# search
arr = range(10)
print arr
print 5 in arr
print arr.index(5)
print arr.count(5)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
True
5
1
# adding elements
arr = range(10)
print arr

arr.append("ten")
print arr

arr.extend([11, 12])
print arr

arr.insert(10, "before ten")
print arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'ten']
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'ten', 11, 12]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'before ten', 'ten', 11, 12]
# removing
arr = range(10)
print arr

print arr.pop()
print arr

print arr.remove(5)
print arr

del arr[0]
print arr

del arr[3:]
print arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9
[0, 1, 2, 3, 4, 5, 6, 7, 8]
None
[0, 1, 2, 3, 4, 6, 7, 8]
[1, 2, 3, 4, 6, 7, 8]
[1, 2, 3]
# reversing
arr = range(10)
print arr

arr.reverse()
print arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# builtin reversed() generator
for elem in reversed(["a", "b", "c"]):
    print elem
c
b
a
# sorting
arr = [5, 7, 1, 10, -1]
print arr
arr.sort()
print arr
arr.sort(reverse=True)
print arr
[5, 7, 1, 10, -1]
[-1, 1, 5, 7, 10]
[10, 7, 5, 1, -1]
# more sorting
arr = ["abc", "defg", "h", "ij"]
print arr
arr.sort(key=lambda elem: len(elem), reverse=True)
print arr
['abc', 'defg', 'h', 'ij']
['defg', 'abc', 'ij', 'h']
# builtin sorted generator
arr = ["abc", "defg", "h", "ij"]
print arr

for elem in sorted(arr, key=lambda elem: len(elem), reverse=True):
    print elem
['abc', 'defg', 'h', 'ij']
defg
abc
ij
h
# zip
first_sequence = range(10, 100, 10)
second_sequence = range(1, 10, 1)

zip(first_sequence, second_sequence)
[(10, 1),
 (20, 2),
 (30, 3),
 (40, 4),
 (50, 5),
 (60, 6),
 (70, 7),
 (80, 8),
 (90, 9)]
# max, min
print max(1, 2, 3)
print max(range(10))
print min(range(10))
print max(range(5, 10), key=lambda val: 2 ** -val)
3
9
0
5
# sum
print sum(range(10))
print sum(range(10), -45)
45
0

Кортеж (tuple) - неизменяемый массив

print (1, 2)
print tuple([1, 2, 3])
a, b = 4, 5
print a, b
(1, 2)
(1, 2, 3)
4 5

Строки


Код

# string literals
print type("abc"), "abc"
print type(u"abc"), u"abc"

print "Funny, isn't it?"
print 'Funny, isn\'t it?'

print 'Quote: "Ahaha"'
<type 'str'> abc
<type 'unicode'> abc
Funny, isn't it?
Funny, isn't it?
Quote: "Ahaha"
# multiline literals
print """This is the multiline
string literal"""
This is the multiline
string literal
# raw strings
print r"\test"
print "\test"
\test
    est
# auto concat adjacent strings and multiple lines
print "first part"\
      " and second part"
first part and second part
# split
print "abcd efg".split(" ")
print "abcd efg hij".split(" ", 1)
print "abcd efg hij".rsplit(" ", 1)
['abcd', 'efg']
['abcd', 'efg hij']
['abcd efg', 'hij']
# join
print " ahaha ".join(["Your", "words", "are", "funny"])
Your ahaha words ahaha are ahaha funny
# check parts of the string
line = "abacaba"
print line.startswith("aba")
print line.endswith("aba")
print line.replace("aca", "AHAHA")
print line.find("aca")
True
True
abAHAHAba
2
# simple formatting examples
print "first argument is {}, second argument is {}".format(1, 2)
print "first argument is {1}, second argument is {0}".format(1, 2)
# error -> print "first argument is {1}, second argument is {}".format(1, 2)
print "My name is {name}".format(name="unknown")
key = "counter"
value = "1"
print "{}={}".format(key, value)
first argument is 1, second argument is 2
first argument is 2, second argument is 1
My name is unknown
counter=1

Пример простого ввода и вывода
# input
line = raw_input()

# ouptut
print line
Hello!
Hello!

Отображения (mappings)

Свойства:


Код

# dict literal
counters = { "a": 1, "b": 2}
print counters

# dict()
print {}
print dict()

# from pairs
key_values = [("a", 1), ("b", 2)]
print dict(key_values)
{'a': 1, 'b': 2}
{}
{}
{'a': 1, 'b': 2}
# lookup element
counters = {"a": 1, "b": 2}
print counters["a"]
print "a" in counters
print counters.get("a", 0)
1
True
1
# lookup error
counters = {"a": 1, "b": 2}
counters["c"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-40-bd0ea5dacece> in <module>()
      1 # lookup error
      2 counters = {"a": 1, "b": 2}
----> 3 counters["c"]

KeyError: 'c'
counters = {"a": 1, "b": 2}
print counters.get("c", None) is None
True
# add element
counters = {"a": 1, "b": 2}
counters["c"] = 3
print counters
{'a': 1, 'c': 3, 'b': 2}
# remove element
counters = {"a": 1, "b": 2}
print counters
del counters["b"]
print counters
print counters.pop("a")
print counters
{'a': 1, 'b': 2}
{'a': 1}
1
{}
counters = {"a": 1, "b": 2}

for key in counters:
    print key, counters[key]

print counters.keys()
print counters.values()
print counters.items()

for key in counters.iterkeys():
    print key

for value in counters.itervalues():
    print value

for key, value in counters.iteritems():
    print key, value

a 1
b 2
['a', 'b']
[1, 2]
[('a', 1), ('b', 2)]
a
b
1
2
a 1
b 2

Множество

Свойства:


Код

# making set
print set()
print set([1, 2, 3])
print set([1, 2, 1, 3, 4, 2, 2, 2])
set([])
set([1, 2, 3])
set([1, 2, 3, 4])
# adding element
elems = set()
print elems
elems.add(1)
print elems
set([])
set([1])
# element lookup
elems = set([1, 2, 3])
print elems
print 1 in elems
set([1, 2, 3])
True
# removing
elems = set([1, 2, 3, 4, 5])
print elems
elems.remove(3) # will throw if not a member
print elems
elems.discard(2) # won't throw an error if not a member
print elems

elems.pop() # arbitrary element
print elems

elems.clear()
print elems
set([1, 2, 3, 4, 5])
set([1, 2, 4, 5])
set([1, 4, 5])
set([4, 5])
set([])
# set operations
elems = set(range(1, 10))
print elems
other_elems = set(range(5, 15))
print other_elems

print elems.intersection(other_elems)
print elems.difference(other_elems)
print elems.symmetric_difference(other_elems)
print elems.issubset(other_elems)
set([1, 2, 3, 4, 5, 6, 7, 8, 9])
set([5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
set([8, 9, 5, 6, 7])
set([1, 2, 3, 4])
set([1, 2, 3, 4, 10, 11, 12, 13, 14])
False
# iteration
elems = set(range(10))
for elem in elems:
    print elem
0
1
2
3
4
5
6
7
8
9