Difference between revisions of "Python:DataTypes"

From wiki
Jump to navigation Jump to search
Line 102: Line 102:
 
   for key2 in sorted(dict[name].keys()):
 
   for key2 in sorted(dict[name].keys()):
 
       print key2,dict[name][key2]  
 
       print key2,dict[name][key2]  
 +
</syntaxhighlight>
 +
Recursively search a key:
 +
<syntaxhighlight lang=python>
 +
def search_dict(data,skey=None):
 +
    result = None
 +
    if skey in data:
 +
        result = data[skey]
 +
    else:
 +
        for key in data:
 +
            if isinstance(data[key],dict):
 +
                result = search_dict(data[key],skey)
 +
    return result
 
</syntaxhighlight>
 
</syntaxhighlight>
  

Revision as of 00:28, 22 December 2018


Object Classes

Lots of things to tell about strings, they have there own string page.

Also for numpy (module for scientific arithmetic) there is a special page

Objects are iterable if they can contain more than 1 ordered objects (string, list, tuple, dict). Objects are mutable if their content can be changed (list, set, dict)

isinstance(<obj>, <class>)
Boolean (returns True or False) to check if <obj> is an instance of <class>

Note: Variables are pointers to objects, not the object itself.

list

Class of iterable, mutable objects. Lists can be compared to arrays in other languages. Lists can contain a mixture of all kind of objects.

lst1 = []
Initialize an empty list
lst1.append(2)
Add the '2' object to the end of lst1
lst1.pop(n)
Remove and return nth element from lst1. Last element if n is not specified.
lst1 = list(object)
Convert object to a list (object is e.g. set, tuple or string)
count = lst1.count[x]
Return the number of occurrences of x in lst1
lst1.sort()
Sort lst1 and return 'None' object
lst2 = sorted(iterable)
Return the iterable object sorted as list

More on sorting e.g. using keys.

set

Class of iterable, mutable objects. Objects added to sets are hashed. Therefor:

  • Only immutable objects can be added to a set.
  • Sets cannot hold duplicate objects (adding an object again does not change the set).
  • Checking if a set holds an object is very fast.
set1 = set()
Initialize an empty set
set1 = set([<values>])
Initialize a set with <values>. Note the list-format of <values>.
set1.add(2)
Add the '2' object to set1. You can add only 1 object at a time.
set1.discard(2)
Remove the '2' object from set1 (returns None object)
diffset = set1 - set2
diffset will have all elements of set1 that are not in set2

Tuple

Class of iterable, immutable objects. Results from database queries are by default returned as tuple.

tpl1 = ()
Initialize an empty tuple

Dictionary or dict

Class of iterable, mutable objects. Dictionary's can be compared to perl hashes.

dict1 = {}
Initialize an empty dictionary.
dict1 = { column1: value1, column2: value2 }
Initialize dictionary with data
if key in dict:
Test if key exists in dict. if dict[key]: will throw a keyerror if it does not exist.
dict1.keys()
List of keys in dict1
dict1.update(dict2)
Add dict2 to dict1. Duplicate keys are overwritten in dict1.
dict1.pop(key)
Remove key from dict1, return dict1[key] if successful, None if key does not exist in dict1.

Code example:

dict = {}
dict["name1"] = {}
dict["name1"]["street"] = "mystreet"
 
for name in dict:
   print name
   for key2 in dict[name]:
      print key2,dict[name][key2]
 
for name in dict:
   print name
   for key2 in sorted(dict[name].keys()):
      print key2,dict[name][key2]

Recursively search a key:

def search_dict(data,skey=None):
    result = None
    if skey in data:
        result = data[skey]
    else:
        for key in data:
            if isinstance(data[key],dict):
                result = search_dict(data[key],skey)
    return result

None

The None object is returned e.g. if nothing is found in a re.search. The None object is not an empty string

Range

Constructor of immutable sequences of integers. Use with list, set, tuple to create the desired object, or for loops.

range(start,stop,step)
Generic format. If you leave out step, step = 1. If only 1 parameter is provided, it is the stop number, start = 0, step = 1
for i in range (2,8,2):
    print(i)

DateTime

Lots more to do than setting timestamps (to be added)

from datetime import datetime
timestamp = datetime.now().strftime("%y%m%d_%H%M%S")

Slicing

You can address all iterable datatypes partly or in a difference sequence.

object[b:e:s]
Generic format where b=Begin (counting starts at 0), e=End, s=Stepsize (negative stepsize starts counting at the end)

Examples:

'last element'[-1]
'elements in reversed order'[::-1]
'element 2,3 and 5'[1:6:2]
'all elements from the second'[1:]