Basic Python/Data Structure

set, count, index, reverse, sort, pop, strip, lstrip, rstrip, round, zip, |, ^, dict, sort, sorted, reverse, math, Queue, LifoQueue

Naranjito 2022. 2. 16. 11:43
  • set

It returns unique items.

my_set={1,2,3,1,2}
print(my_set)

>>>
{1, 2, 3}
your_set=set([1,2,3,2,1])
your_set

>>>
{1, 2, 3}
set('abracadabra')

>>>
{'a', 'b', 'c', 'd', 'r'}

 

  • count

It returns the number of elements with the specified value.

fruits = ['apple', 'banana', 'cherry','banana', 'apple']
fruits.count('apple')

>>>
2

 

  • index(x,n)

Return zero-based index in the list of the first item whose value is equal to x.

Find next item starting a position n.

f=['orange','apple','pear','banana','kiwi','apple','banana']
f.index('orange')

>>>
0

f.index('banana',4)

>>>
6

 

  • reverse

Reverse the elements of the list in place.

f.reverse()
f

>>>
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']

 

  • sort

Sort the items.

f.sort()
f

>>>
['apple', 'apple', 'banana', 'banana', 'kiwi', 'orange', 'pear']

 

  • pop

Remove and return the last item in the list.

f.pop()

>>>
'pear'

 

  • A list comprehension(DOUBLE FOR)
[(x,y) for x in [1,2,3] for y in [3,1,4] if x!=y]

>>>
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

It is equivalent to

combs=[]
for x in [1,2,3]:
    for y in [3,1,4]:
        if x!=y:
            combs.append((x,y))
combs

 

Another example of DOUBLE FOR.

vec=[[1,2,3],[4,5,6],[7,8,9]]
[num for elem in vec for num in elem]

>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]

 

Another example of DOUBLE FOR.

matrix=[[1,2,3,4],[5,6,7,8],[9,10,11,12],]
[[row[i] for row in matrix] for i in range(4)]

>>>
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

 

  • strip

Remove spaces at the beginning and at the end of the string.

txt="     banana     "
x=txt.strip()
x
>>>
'banana'

txt
>>>
'     banana     '

txt=",,,,,rrttgg.....banana....rrr"
x=txt.strip(",.grt")
x
>>>
'banana'

 

  • lstrip

Left Strip, remove left white spaces.

f=['  banana', '  loganberry ', 'passion fruit  ']
[w.lstrip() for w in f]

>>>
['banana', 'loganberry ', 'passion fruit  ']

 

  • rstrip

Right Strip, remove right white spaces.

[w.rstrip() for w in f]

>>>
['  banana', '  loganberry', 'passion fruit']

 

  • round(num, digits)

It returns a floating point number.

[str(round(pi, i)) for i in range(1,6)]

>>>
['3.1', '3.14', '3.142', '3.1416', '3.14159']

 

  • zip

It returns the two tuples as pairwise.

keys = ("apple", "pear", "peach")
vals = (300, 250, 400)
result=zip(keys,vals)
result=dict(result)
result
>>>
{'apple': 300, 'pear': 250, 'peach': 400}
list(zip(*matrix))

>>>
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

 

  • |

It returns letters in a or b or both.

a=set('abracadabra')
b=set('alacazam')

a|b
>>>
{'a', 'b', 'c', 'd', 'l', 'm', 'r', 'z'}

 

  • ^

It returns letters in a or b but not both.

a^b

>>>
{'b', 'd', 'l', 'm', 'r', 'z'}

 

  • dict
dict([('s',4123),('g',1532),('j',4608)])

>>>
{'s': 4123, 'g': 1532, 'j': 4608}

It is equivalent to

dict(s=4123, g=1532, j=4608)

 

  • sort

It sorts the elements in ascending order by default. Alternatively, you can also use sorted() function for the same purpose.

data = [2, 4, 3, 1, 5, 10, 9]
data.sort()
data
>>>
[1, 2, 3, 4, 5, 9, 10]

 

  • sorted

Same as sort.

data = [2, 4, 3, 1, 5, 10, 9]
sorted_data=sorted(data)
print(sorted_data)
>>>
[1, 2, 3, 4, 5, 9, 10]

  • key

It takes a single argument and returns a key to use for sorting purposes. 

student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]
sorted(student_tuples, key=lambda student: student[2])   # sort by age
>>> [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

 

  • reverse

It reverses the elements of the list.

a=['1','2','3']
a.reverse()
a
>>>
['3', '2', '1']

 

  • sort(reverse=True)

It sorts the elements in dscending order.

a=['1','2','3']
a.sort(reverse=True)
a
>>>
['3', '2', '1']

 

  • reversed

It reversed the elements.

a=['1','2','3']
b=reversed(a)
list(b)
>>>
['3', '2', '1']

 

  • math
import math
raw=[56.2, float('Nan'), 51.7, 55.3,52.5, float('Nan'), 47.8]
fil=[]
for value in raw:
    if not math.isnan(value):
        fil.append(value)
fil

>>>
[56.2, 51.7, 55.3, 52.5, 47.8]

 

  • Queue

It stores items in First In First Out.

import queue

data_queue=queue.Queue()
data_queue.put(1)
data_queue.put(2)

data_queue.get()
>>>
1

data_queue.get()
>>>
2

 

  • LifoQueue

Last Out.

 

data_queue=queue.LifoQueue()
data_queue.put(1)
data_queue.put(2)

data_queue.get()
>>>
2

data_queue.get()
>>>
1