list)tuple)dict)set)Какво ви показахме предния път?
for age in range(1, 10000):
if age > 169:
print("You reached super-human limits!")
break
if age % 17 == 1:
print("So lucky!")
continue
print("So ordinary my leg hurts.")
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n - 1)
things = ['spam', 42, 3.14] things[1] = 'baba' have_eggs = 'eggs' in things more_things = things + ['ham', 'cheese'] del more_things[2]
>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> numbers[3:9] [3, 4, 5, 6, 7, 8] >>> numbers[0:10:2] [0, 2, 4, 6, 8] >>> numbers[3:9] = [-1, -1, -1] [0, 1, 2, -1, -1, -1, 9] >>> numbers[::2] = ['w', 'x', 'y', 'z'] ['w', 1, 'x', -1, 'y', -1, 'z']
Какво ще изведе този код?
foods = ['spam', 'eggs', 'ham'] things = foods things[1] = 'chips' print(foods[1])
А този?
a = ['spam', 'eggs', 'ham'] b = a c = a[:] print(a is b, a is c) print(a == b, a == c) b[1] = 'milk' print(a is b, a is c) print(a == b, a == c)
Или пък този?
cheese = ['cheddar', 'red leicester', 'emmental'] cheese[1] = cheese food = cheese[1][:] cheese[2] = 'limburger' print(food[2]) print(food[1][2])
(immutable) списъци
primes = (2, 3, 5, 7, 11, 13)
(2,), иначе ще се сметне за израза 2slice-вате, но не и променяте:
("Foo", "Bar", ("Spam",), ("More", "Spam"))
+*1 in (1, 2)for x in (1, 2):.index.countАко имате n-торка, съдържаща само имена от лявата страна на присвояване, може да постигнете интересни ефекти:
>>> (a, b) = 1, 2 >>> print(a) 1
Всъщност скобите не са задължителни:
>>> a, b = 1, 2 >>> a, b = b, a >>> print(a) 2 >>> print(b) 1
Или:
>>> numbers = (1, 2, 3) >>> a, b, c = numbers
В този ред на мисли, същото го могат и списъците
>>> numbers = [1, 2, 3] >>> [a, b, c] = numbers
Сравняват се лексикографски:
>>> (1, 2) < (1, 3) True >>> (1, 2) < (1, 2) False >>> (1, 2) < (1, 2, 3) True >>> [1, 2] < [1, 3] True >>> (1, 2) < [1, 3] # tuple vs. list # поражда грешка: # TypeError: unorderable types: tuple() < list()
set([1, 2, 3]){1, 2, 3}set(), а не {}
>>> numbers = {1, 2, 3, 8, 2}
>>> numbers
{8, 1, 2, 3}
>>> 2 in numbers
True
>>> 4 in numbers
False
>>> numbers.add(4)
>>> 4 in numbers
True
>>> numbers.remove(1)
>>> numbers
{8, 2, 3, 4}
>>> {1, 2, 3} | {2, 3, 4}
{1, 2, 3, 4}
>>> {1, 2, 3} & {2, 3, 4}
{2, 3}
>>> {1, 2, 3} - {2, 3, 4}
{1}
>>> {1, 2, 3} ^ {2, 3, 4}
{1, 4}
>>> {1, 2, 3} < {2, 3, 4}
False
>>> {2, 3} < {2, 3, 4} # < - подмножество
True
>>> {2, 3} == {2.0, 3}
True
>>> {1, 2}.isdisjoint({3, 4})
True
list, set и tuple
>>> set([1, 2, 3, 8, 2])
{8, 1, 2, 3}
>>> list({1, 2, 3})
[1, 2, 3]
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> list((1, 2, 3))
[1, 2, 3]
languages = {
'Spain': 'Spanish',
'Great Britain': 'English',
'Italy': 'Italian',
'Mexico': 'Spanish',
'France': 'French',
'USA': 'English',
}
print(languages['Mexico']) # Spanish
capitals = {
'Germany': 'Berlin',
'France': 'Paris',
'Brazil': 'Rio de Janeiro',
'Malaysia': 'Kuala Lumpur',
}
print(capitals['Brazil'])
# Rio de Janeiro
capitals['Brazil'] = 'Brazil'
print(capitals['Brazil'])
# Brazil
capitals['Sweden'] = 'Stockholm'
print(capitals['Sweden'])
# Stockholm
del capitals['Malaysia']
capitals['Malaysia']
# KeyError: 'Malaysia'
>>> capitals = {
'Germany': 'Berlin',
'France': 'Paris',
'Brazil': 'Rio de Janeiro',
'Sweden': 'Stockholm',
}
>>> capitals.get('Assyria')
None
>>> capitals.get('Assyria', "I don't know")
"I don't know"
>>> 'Sweden' in capitals
True
>>> list(capitals.keys())
['Brazil', 'Sweden', 'Germany', 'France']
>>> list(capitals.values())
['Rio de Janeiro', 'Stockholm', 'Berlin', 'Paris']
>>> len(capitals)
4
>>> numbers = {
"One": "I",
"Two": "II",
}
>>> list(numbers.items())
[('One', 'I'), ('Two', 'II')]
>>> numbers.update({"Three": "III", "Four": "IV"})
>>> numbers
{'Four': 'IV', 'Three': 'III', 'Two': 'II', 'One': 'I'}
>>> numbers.pop('Four')
'IV'
>>> numbers
{'Three': 'III', 'Two': 'II', 'One': 'I'}
>>> {1: 1, 2: 2} == {2: 2, 1: 1}
True
>>> numbers = {"One": "I", "Two": "II"}
>>> numbers_copy = numbers.copy()
>>> numbers_copy
{'Two': 'II', 'One': 'I'}
>>> numbers
{'Two': 'II', 'One': 'I'}
>>> numbers.clear()
>>> numbers_copy
{'Two': 'II', 'One': 'I'}
>>> numbers
{}
Чрез наименовани параметри към конструктора (не питайте):
>>> dict(france="Paris", italy="Rome")
{'italy': 'Rome', 'france': 'Paris'}
Чрез списък от двойки
>>> dict([('One', 'I'), ('Two', 'II')])
{'Two': 'II', 'One': 'I'}
Чрез списък от ключове и стойност по подразбиране
>>> dict.fromkeys([1, 2, 3], 'Unknown')
{1: 'Unknown', 2: 'Unknown', 3: 'Unknown'}
обект → число==immutable