This is a training to become a data scientist using Python. The one that controls the type does the main class of Python by controlling everything.
** PREV ** → [Python] Road to snake charmer (2) Basics of Python ** NEXT ** → [Python] Road to a snake charmer (4) Tweaking Numpy
class | Description | Classification | Instance example |
---|---|---|---|
object | object type | object | object() |
bool | Logical type | Logical value | True, False |
int | Integer type | Numerical value | 26, 0b11010, 0o32, 0x1a |
float | Floating point type | Numerical value | 3.1415, 1.5e-3, 1/2 |
complex | Complex type | Numerical value | 1j, 1.1+2.3j |
tuple | Tuple type | sequence | (), (1,), (True,False) |
list | List type | sequence | [],[1], [True,False] |
str | String type | sequence | 'man',"man",'Man',"Man" |
bytes | Byte string type | sequence | b'man', b'¥xe4¥xba¥xba' |
bytearray | Byte array type | sequence | bytearray(b'man') |
range | Range type | Iterator | range(1,10,2) |
dict | Dictionary type | mapping | {}, {'y':2014,'m':12,'d':25} |
set | Collective type | set | {1,3,5,7,9} |
function | Functional type | function | lambda x:x**2 |
Use type ()
.
In [1]: type('man')
Out[1]: str
Alternatively, use ʻis instance ()`.
In [2]: isinstance('man', str)
Out[2]: True
In [3]: isinstance('man', bytes)
Out[3]: False
ʻIs instance (x, X)is True even if
type (x)is a subclass of
X`.
That is, all classes are subclasses of the object class.
In [4]: isinstance('man', object)
Out[4]: True
In [5]: issubclass(str, object)
Out[5]: True
Generally, it can be converted by putting the conversion source in the first argument of the conversion destination class.
In [6]: float(1) #int to float
Out[6]: 1.0
In [7]: int(-1.9) #float to int
Out[7]: -1
In [8]: complex(0) #int to complex
Out[8]: 0j
In [9]: list((1, 2, 3)) #tuple to list
Out[9]: [1, 2, 3]
In [10]: tuple([1, 2, 3]) #list to tuple
Out[10]: (1, 2, 3)
In [11]: list(range(5)) #range to list
Out[11]: [0, 1, 2, 3, 4]
In [12]: list('abc') #str to list
Out[12]: ['a', 'b', 'c']
bool
True and false of bool class (logical type) are represented by True
, False
.
Operators for negation, conjunction and disjunction are not
, ʻand, ʻor
.
In [13]: not True, True and True, True or False
Out[13]: (False, True, True)
All objects can be cast to bool. In Python, conversion to implicit logical types is done in various situations, such as conditional statements.
In [14]: bool(0), bool(0.1), bool(()), bool([]), bool({}), bool({0})
Out[14]: (False, True, False, False, True)
The logical product and OR of integers returns the last integer in the evaluation procedure. In [16] is the logical product and OR of each bit of an integer.
In [15]: 3 and 6, 3 or 6, 1 and 0
Out[15]: (6, 3, 0)
In [16]: 3 & 6, 3 | 6
Out[16]: (2, 7)
int, float
There is no upper limit to the int type.
In [26]: 10 ** 30
Out[26]: 1000000000000000000000000000000
10 / 5
becomes float
, 10 // 5
becomes ʻint`.
In [27]: 10 / 5, 10 // 5
Out[27]: (2.0, 2)
Seeking quotient and remainder.
In [28]: 10 // 3, 10 % 3
Out[28]: (3, 1)
list, tuple
--list
can change elements and subsequences
--tuple
cannot be changed
list
Generate list
In [29]: a = [10, 20, 30, 40, 50]
You can refer to it by index.
You can refer to the end of the list with -1
.
In [30]: a[0], a[-1]
Out[30]: (10, 50)
Of course you can change it.
In [31]: a[0], a[-1] = 11,51
You can use a function called slicing for sequences.
#String object[Starting index:End index]
In [32]: a[1:4]
Out[32]: [20, 30, 40]
You can specify a step in the third argument of the slice. If you use this, you can skip the specified number and refer to it.
In [33]: a[::2]
Out[33]: [11, 30, 51]
tuple
Generate tuple
In [33]: a = (10,20,30,40,50)
You can also refer to tuple
by index.
The () in tuple
can be omitted unless misinterpreted.
In [34]: a[0], a[-1]
Out[34]: (10, 50)
The change will result in an error.
In [35]: a[0] = 11
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-45-1ffcdc5ca638> in <module>()
----> 1 a[0]=11
TypeError: 'tuple' object does not support item assignment
Can be combined.
In [36]: a, b = (1,2),(True,'Japan',(None,'dog'))
In [37]: a + b
Out[37]: (1, 2, True, 'Japan', (None, 'dog'))
Cannot be added.
In [38]: a.append(10)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-52-fb2e87d24477> in <module>()
----> 1 a.append(10)
AttributeError: 'tuple' object has no attribute 'append'
You might think that you just restricted it to list
, but tuple
has the following meanings.
--Can be the key of dict
(dictionary)
--Because it is not mutable, it can be processed faster than list
.
--tuple
originally meant to" simply "combine multiple objects into one
str, bytes, bytearray
str
(string) always means Unicode.
In contrast, bytes
and bytearray
are simple byte sequences.
The difference between bytes
and bytearray
is the same as the difference between tuple
and list
.
The reference method of the character string is basically the same as list and tuple.
In [53]: a, b = 'ABCDE','FG'
In [54]: a[0],a[-1],a[-2],a[1:4]
Out[54]: ('A', 'E', 'D', 'BCD')
You can include line breaks with triple quotes.
In [55]: s = '''
....: #include <stdio.h>
....: int main(){
....: printf("hello world\n");
....: return 0;
....: }
....: '''
In [56]: s
Out[56]: '\n #include <stdio.h>\n int main(){\n printf("hello world\n");\n return 0;\n}\n'
dict
In list
, index was an integer starting from 0, but in dict
(dictionary type), integers, strings, tuples, etc. can be used as the key corresponding to this index.
In [61]: exts={'py':'Python','rb':'Ruby','pl':'Perl'}
In [62]: for key in exts:
....: value=exts[key]
....: print(key,value)
pl Perl
py Python
rb Ruby
You can retrieve the key and value together using ʻitems ()`.
In [63]: for key,value in exts.items():
....: print(key,value)
pl Perl
py Python
rb Ruby
Use in to see if the key is included in the dict.
In [64]: 'py' in exts, 'c' in exts
Out[64]: (True, False)
** NEXT ** → [Python] Road to a snake charmer (4) Tweaking Numpy
Recommended Posts