Python basics ②

I will continue writing from the last time.

List type

This is also basic It is a method to put multiple data in one variable.

List basics

You can enter data directly It is also possible to enter it as a variable as shown below You can also mix character strings and numbers.

apple = 4
grape = 'grape'
mikan = 6

fruits = [apple, grape, mikan]

print(fruits)
#output[4,grape,6]

Multiple list

How to put a list in a list.


rei = [[1.2],[3,4],[5.6]]
#The above is an example of usage type.


fruits_name_1 = "Apple"
fruits_num_1 = 2
fruits_name_2 = "Mandarin orange"
fruits_num_2 = 10

fruits = [[fruits_name_1, fruits_num_1], [fruits_name_2, fruits_num_2]]


print(fruits)
#output: [["Apple", 2], ["Mandarin orange", 10]]

Get a value from the list.

Indexes (numbers) are assigned to the list. It starts from 0 and can be retrieved by specifying a numerical value.

As a precaution, set the last to -1 You can also take out -2, -3 in order.

ListSample = [1, 2, 3, 4]
print(ListSample [1]) 
#"2" with index 1 is output

ListSample = [1, 2, 3, 4]
print(ListSample [-2]) 
#The second "3" from the back of the list is output

Fetch values from a list from a list.

The rule for fetching multiple lists.

1, Number: Extract from the specified number with 2: Take out the number to the front of the number (in the case of-, count from the left) If the number is 3, or more, until the end of the current situation

alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(alphabet[1:5]) 
#Indexes 1 to 4["b", "c", "d", "e"]Is output

print(alphabet[:5]) 
#From the beginning to index 4["a", "b", "c", "d", "e"]Is output

print(alphabet[6:]) 
#Index 6 to the end["g", "h", "i", "j"]Is output

print(alphabet[0:20]) 
#Since the index is up to 9, if you specify up to 19,
# ["a","b", "c", "d", "e", "f", "g", "h", "i", "j"]And everything is output

alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(alphabet[1:-5]) 
#Index 1 to 6th from the back["b", "c", "d", "e"]Is output

Overwrite and add list

As a rule

alphabet = ["a", "b", "c", "d", "e"]
alphabet[0] = "A" #Overwrite the value of the first element
print(alphabet) 
# ["A", "b", "c", "d", "e"]Is output


alphabet = ["a", "b", "c", "d", "e"]
alphabet[1:3] = ["B", "C"] #Assign values to indexes 1 and 2, respectively
print(alphabet) 
# ["a", "B", "C", "d", "e"]Is output


alphabet = ["a", "b", "c", "d", "e"]
alphabet.append("f") #Use append to add only one
print(alphabet) 
# ["a", "b", "c", "d", "e", "f"]Is output
#Note that append cannot add multiple elements. If you want to add multiple values, click "+Use to concatenate the lists.

alphabet = ["a", "b", "c", "d", "e"]
alphabet += ["f","g"] #When adding more than one+use
print(alphabet) # ["a", "b", "c", "d", "e", "f", "g"]Is output

Remove element from list

del List Use Index.

alphabet = ["a", "b", "c", "d", "e"]
del alphabet[3:] #Delete elements after index 3
print(alphabet) # ["a", "b", "c"]Is output
#You can also specify the deletion range by slicing.

alphabet = ["a", "b", "c", "d", "e"]
del alphabet[1:3] #Delete elements index 1-2
print(alphabet) # ["a", "d", "e"]Is output

Copy of list

As a caveat If you just assign a list variable to a list variable Recognized as the same content, If you change the assignment destination, the assignment source will also change.

If you want to change only the contents of the list

list() #Use the one on the left.


#Variable as it is
alphabet = ['a', 'b', 'c']
alphabet_copy = alphabet # alphabet_Assign the value of alphabet to copy
alphabet_copy[0] = 'A' # alphabet_Overwrite the first value of copy
print(alphabet_copy)
print(alphabet)

 ['A', 'b', 'c']
 ['A', 'b', 'c']


# list()Only the contents using
alphabet = ['a', 'b', 'c']
alphabet_copy = list(alphabet)
alphabet_copy[0] = 'A'
print(alphabet_copy) 
print(alphabet) 

#The output is as follows.

['A', 'b', 'c']
['a', 'b', 'c']

Dictionary type

This is also called a hash. It is treated as a set of key and value.

The caveat is to use {}.

city = {"Key 1": "Value 1", "Key 2": "Value 2"}

Extraction of dictionary

Call by specifying the key.

dic ={"Japan": "Tokyo", "Korea": "Seoul"}
print(dic["Japan"]) 
#Output as Tokyo

Overwrite and add dictionaries

Both operations are the same Operate by specifying the key. If there is a specified key, it will be overwritten, otherwise it will be added.

Overwrite


dic ={"Japan":"Tokyo","Korea":"Seoul"}
dic["Japan"] = "Osaka"
print(dic) 

# {"Japan": "Osaka", "Korea": "Seoul"}Is output

add to


dic ={"Japan":"Osaka","Korea":"Seoul"}
dic["China"] = "Beijing"

print(dic) 
# {"Japan": "Osaka", "Korea": "Seoul", "China": "Beijing"}Is output

Delete dictionary elements

del You can delete the element of the specified key by the description of the dictionary name ["key you want to delete"].

Delete


dic = {"Japan": "Tokyo", "Korea": "Seoul", "China": "Beijing"}
del dic["China"] 
#Delete the specified element
print(dic) 
# {"Japan": "Tokyo", "Korea": "Seoul"}Is output.

while statement

Syntax to do until the condition is not met

while conditional expression: What happens when the conditional expression is True

while


n = 2
while n >0: #If n is greater than 0, perform the following processing
    print(n)
    n -= 1 #n-1

#Output result 1 2

while and if statements

With the matching technique, it continues until a certain condition.

while x != 0:
    #The process executed in while is the process of subtracting 1 from the variable x and the process of outputting after subtracting 1.
    x -= 1
    if x != 0:
        print(x)
    else:
        print("Bang")

for statement

Multiple data such as list and dictionary type Syntax to retrieve from variable

Write with "for variable in list:".

nimals = ["tiger", "dog", "elephant"]
for animal in animals: #Number of elements contained in animals = Repeat processing 3 times
    print(animal)
#Output result
tiger
dog
elephant

break Repeated end processing

break


storages = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n in storages: #Number of elements contained in storages=Repeat processing 10 times
    print(n)
    if n >= 5: #When n becomes 5 or more, perform the following processing
        print("Since n is 5 or more, the process ends.")
        break #End the processing of the for statement

continue Used when you want to skip processing

continue


storages = [1, 2, 3, 4, 5, 6] #Number of elements contained in storages=Repeat processing 6 times
for n in storages:
    if n < 3: #If n is less than 3, no processing is performed(skip)
        continue
    print(n)

#Output result
3
4
5
6

Appendix

enumerate() It is used when you want to display the index in the for statement.

index display


list_ = ["a", "b"]
for index, value in enumerate(list_): #Get index and value of list
    print(index, value)
#Output result
0 a
1 b

Multiple list loop

It can be output by preparing the variable of the assignment destination.

Multiple list loop


list_ = [[1, 2, 3], [4, 5, 6]]
for a, b, c in list_:
    print(a, b, c)
#Output result
1 2 3
4 5 6

However, if the original data does not contain the number statement data, an error will occur.

Multiple list loop error


list_ = [[1, 2, 3], [4, 5]]
for a, b, c in list_:
    print(a, b, c) #Get an error
#Output result
not enough values to unpack (expected 3, got 2)

Dictionary type loop

By using a function called items () Both keys and values can be stored in variables.

Dictionary-shaped loop


fruits = {"strawberry": "red", "peach": "pink", "banana": "yellow"}
for fruit, color in fruits.items(): 
#The key is stored in a variable called fruit and the value is stored in a variable called color.
        print(fruit+" is "+color)

#Output result
strawberry is red
peach is pink
banana is yellow

Recommended Posts

Python basics ⑤
Python basics ④
Python basics ③
Python basics
Python basics
Python basics
Python basics ③
Python basics ②
Python basics ②
Python basics: list
Python basics memorandum
#Python basics (#matplotlib)
Python basics: dictionary
Basics of Python ①
Basics of python ①
Python slice basics
#Python basics (scope)
#Python basics (#Numpy 1/2)
Python array basics
Python profiling basics
Python #Numpy basics
Python basics: functions
#Python basics (class)
Python basics summary
Python: Unsupervised Learning: Basics
Python
Basics of Python scraping basics
Python basics 8 numpy test
Errbot: Python chatbot basics
#Python DeepLearning Basics (Mathematics 1/4)
Python basics: Socket, Dnspython
# 4 [python] Basics of functions
Basics of python: Output
python: Basics of using scikit-learn ①
Python basics: conditions and iterations
Paiza Python Primer 4: List Basics
Basics of Python × GIS (Part 1)
kafka python
Basics of Python x GIS (Part 3)
python + lottery 6
Python Summary
Built-in python
Paiza Python Primer 5: Basics of Dictionaries
Python comprehension
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
SNS Python basics made with Flask
Python service
python tips
Linux basics
Python memo
Python comprehension
Python Singleton
NumPy basics
Python Memorandum 2
Python increment
atCoder 173 Python
[Python] function
Python installation