Zbiory w Python


In [1]:
l = [1,2,3,3,3,4,5,44]

In [2]:
s = set(l)

In [6]:
s.intersection([33,44,1,1])


Out[6]:
{1, 44}

In [8]:
s.union([111,2,3])


Out[8]:
{1, 2, 3, 4, 5, 44, 111}

nie można indeksować zbioru


In [10]:
s[1]


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-88de191fe097> in <module>()
----> 1 s[1]

TypeError: 'set' object does not support indexing

ale można iterować po jego elementach


In [11]:
for el in s:
    print(el)


1
2
3
4
5
44

sortowanie


In [14]:
l = [13,2,3,4]

In [15]:
sorted(l)


Out[15]:
[2, 3, 4, 13]

In [16]:
l


Out[16]:
[13, 2, 3, 4]

In [17]:
l.sort()

In [18]:
l


Out[18]:
[2, 3, 4, 13]

In [19]:
l.sort(key=lambda x:1/x)

In [20]:
l


Out[20]:
[13, 4, 3, 2]

In [21]:
def f(x):
    return 1/x

In [22]:
l.sort(key=f)

In [23]:
l


Out[23]:
[13, 4, 3, 2]

In [33]:
l = [("a",1),(2,3),(-1,3)]
l


Out[33]:
[('a', 1), (2, 3), (-1, 3)]

In [34]:
def f(x):
    return x[1]

In [32]:
l.sort()


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-b56eb6767f72> in <module>()
----> 1 l.sort()

TypeError: unorderable types: int() < str()

In [35]:
l.sort(key=f)

In [36]:
l


Out[36]:
[('a', 1), (2, 3), (-1, 3)]

In [47]:
l = [ (x,y) for x in range(44) for y in range(44) ]

In [48]:
def f(X):
    return( X[0]**2+ X[1]**2)

In [49]:
l.sort(key=f)

In [50]:
%matplotlib inline
import matplotlib.pyplot as plt

In [54]:
l1 = l
plt.plot([x_[0] for x_ in l1],[x_[1] for x_ in l1],'o')
l1 = l[:230]
plt.plot([x_[0] for x_ in l1],[x_[1] for x_ in l1],'or')


Out[54]:
[<matplotlib.lines.Line2D at 0x7f777b826be0>]

In [86]:
l = [1,2,3,4,5]
k = -1

In [87]:
l[:-k]


Out[87]:
[1]

In [88]:
l[-k:]


Out[88]:
[2, 3, 4, 5]

In [89]:
l[-k:]+l[:-k]


Out[89]:
[2, 3, 4, 5, 1]

In [ ]:


In [ ]: