I will write an article for beginners of python3 several times. Basically, it is an article compiled by subscribing to Introduction to O'Reilly Books Python3. This is a memo for my review, but I posted it because I thought it might be useful for someone. The reader is intended for beginners in Python programming.
This time, we will summarize Chapter 2 "Numeric values, character strings, variables" / Chapter 3 "Lists, tuples, dictionaries, sets".
If you have learned other languages in Chapter 2, you don't need to know anything in particular. The only thing I can say is that I can declare it without worrying about the type ...
print(__import__('keyword').kwlist) #List of reserved words
for funcs in dir(__builtins__):
print(funcs) #List of predefined built-in functions
str = "hoge" #Predefined built-in functions can be overridden(Danger)
print(str) # hoge
str(2016) # TypeError
# None = "huga" #
\
(backslash)\ n
sample.py
foo = x if (x >= 0) else -x #Python ternary operator
sample.c
foo = if (x >= 0) ? x : -x; //c,java,Ternary operators such as js
Expression | meaning |
---|---|
[0] | Get the first (head) of an array / character string |
[5] | Get the 6th array / string |
[0:5] | Get the 1st to 5th of the array / character string (not including the 6th) |
[:5] | Get the 1st to 5th of the array / character string (from the beginning if the start position is omitted) |
[5:] | Get from the 6th to the end of the array / character string (until the end if the end position is omitted) |
[:] | Get all arrays / strings (from start to finish) |
[-1] | Get the first (last) counting from the end of the array / character string |
[-5:-1] | Get from the 5th to the 2nd from the end counting from the end of the array / character string ([-1]Does not include) |
[::5] | Get array / character string every 5 steps |
[::-5] | Get array / character string every 5 steps from behind |
[::-1] | Get array / string from reverse order |
operator | meaning | Example | result |
---|---|---|---|
+ | Addition | 5+3 | 8 |
- | Subtraction | 5-3 | 2 |
* | Multiply | 5*3 | 15 |
/ | division | 5/3 | 1.6 |
// | Integer division (truncation) | 5//3 | 1 |
% | Surplus | 5%3 | 2 |
** | Exponentiation | 5**3 | 125 |
Expression | meaning |
---|---|
len(var) | var length |
var.split(",") | var (string)","Returns an array separated by |
",".join(var) | var (string or string array)","Returns a string concatenated with |
var.replace(",", "") | Replaces var (string) and returns a new string(In this example","To""Replace with) |
If you have learned other languages in Chapter 3, there seems to be no problem. However, there is a Python-like writing style (a writing style that makes good use of iterators). At first, you may feel strange about how to write a "for statement". Once you get used to it, it is convenient to use "in" to access the elements in the array. </ Font color>
two_dim_array = [["hoge", "huga"], [0, 1, 2], False] #List in list
print(two_dim_array[1][0]) # output = 0
list_sample = ["hoge", 0, False]
tuple_sample = ("hoge", 0, False)
dict_sample = {0: "hoge", "huga": 0, 1: False}
set_sample = set("hoge", 0, False)
name | How to write |
---|---|
list | foo = ['tom', 'mike', 'nancy', 'jenny', 'jack'] |
Tuple | foo = ('tom', 'mike', 'nancy', 'jenny', 'jack') |
dictionary | foo = {'tom': 20, 'mike': 21, 'nancy': 'unknown', 'jenny': 12, 'jack': 55} |
set | foo = set('tom', 'mike', 'nancy', 'jenny', 'jack') |
- All elements in the array have the same type
- Fixed array length (fixed length array)
- The number of elements in each dimension of the array is the same
Also, if you want to use it for writing without using numpy, you can also use arr = [[]]
.
It may be a deprecated anti-pattern, so check it out.
function | meaning |
---|---|
append( val ) | Add one element to the end of the list |
extend( arr ) | Add array (multiple elements) to the end of the list |
insert( index, val ) | Add element to specified index in list |
del( index ) | Delete the element of the list specified by the index |
remove( val ) | Remove the element with the specified value from the list |
pop() | Element pop |
index( val ) | Get index of element with specified value from list |
count( val ) | Get the number of elements with the specified value in the list |
join( arr ) | Converting a list to a string (inverse to the split function) |
sort( reverse= True/False ) | Sort the list (ascending if numerical),Alphabetical order for character strings) |
len( arr ) | Get the number of elements in the list |
function | meaning |
---|---|
update( dict ) | Combine dictionaries |
del( key ) | Delete the element with the specified key |
clear( ) | Delete all elements |
dict_sample = {"red": 100, "green": 0, "blue": 200}
dict_sample2 = {"cyan": 50, "magenta": 60, "yellow": 70, "key_plate": 80}
dict_sample.update(dict_sample2) #Combine dictionaries
# > dict_sample = {"red": 100, "green": 0, "blue": 200, "cyan": 50, "magenta": 60, "yellow": 70, "key_plate": 80}
dict_sample["black"] = 123 #If the key is not duplicated, it will be added
# > dict_sample = {"red": 100, "green": 0, "blue": 200, "cyan": 50, "magenta": 60, "yellow": 70, "key_plate": 80, "black": 123}
dict_sample["red"] = 123 #If the key is duplicated, it will be overwritten
# > dict_sample = {"red": 123, "green": 0, "blue": 200, "cyan": 50, "magenta": 60, "yellow": 70, "key_plate": 80, "black": 123}
function | Calculation | meaning | Example |
---|---|---|---|
set1.union( set2 ) | set1 | set2 | Union | {1,2,3} | {2,4,6} ⇒ {1, 2, 3, 4, 6} |
set1.intersection( set2 ) | set1 & set2 | Product set (intersection) | {1,2,3} & {2,4,6} ⇒ {2} |
set1.difference( set2 ) | set1 - set2 | Difference set | {1,2,3} - {2,4,6} ⇒ {1, 3} |
set1.symmetric_difference( set2 ) | set1 ^ set2 | Exclusive OR (belongs to only one) | {1,2,3} ^ {2,4,6} ⇒ {1, 3, 4, 6} |
The Python for statement does not implement a combination of "initialization expression; continuation conditional expression; reinitialization expression". Therefore, do not write in C, C ++, etc. It is similar to the writing method that retrieves the values contained in all the elements of an array or dictionary, like the for-each statement provided by JavaScript, Java, etc.
list_sample = ["hoge", "huga", "hage"]
#Python for statement anti-patterns
for x in range(0, len(list_sample)):
print(list_sample[x]) #Display the elements of the array one by one
#Python for statement pattern
for x in list_sample:
print(x) #Display the elements of the array one by one
As for the dictionary, it can be combined well with the for statement to retrieve the values contained in all the elements.
dict_sample = {"red": 100, "green": 0, "blue": 200}
#Python for statement pattern(Dictionary key only)
for k in dict_sample.keys():
print(k) #Display dictionary keys one by one
#Python for statement pattern(Dictionary value only)
for v in dict_sample.values():
print(v) #Display dictionary values one by one
#Python for statement pattern(Dictionary key,value both)
for k, v in dict_sample.items():
print(k + ":" + str(v)) #Display the contents of the dictionary one by one
in is often used as a conditional expression. You can judge whether or not there is a specified element in a list, tuple, dictionary, or set. (In the case of a dictionary, judgment of the presence or absence of key)
list_sample = ["hoge", "huga", "hage"]
if "hoge" in list_sample: # True
pass
Recommended Posts