[Python] I tried to summarize the array, dictionary generation method, loop method, list comprehension notation

I tried to summarize the python array, dictionary generation method, and loop method. When learning a new language, I would like to suppress the arrangement, dictionary generation method, and loop method in a hurry, so I think it would be convenient if such information is gathered, and this article also serves as a memorandum for myself. I posted. We hope that it will be helpful for those who have recently started using python, and that it can be used as a memorandum.

Array loop

array.py


#Array generation
arr = [] #Empty array generation
arr = [1, 2, 3] #Array generation with elements

#Add array elements from 1 to 5
# ※ range(start, stop)Start-stop-Up to 1 is repeated.
#If start is not specified, it will start from 0.
for i in range(1, 6):
    arr.append(i)

#Array loop
for val in arr:
    print(f"val:{val}")

#Loop of array with index
for index, val in enumerate(arr):
    print(f"index:{index}, val:{val}")

I often misspell ʻenumerate` when I want to loop with an index. I'm going to copy and paste it to myself. ..

dictionary loop

dict.py


dic = {} #Empty dictionary generation
dic = {"key1": 1, "key2": 2}  #Generate dictionary with elements

#Add dictionary
for i in range(1, 6):
    key = f"key{i}"
    dic[key] = i

#Loop dictionary key
for key in dic.keys():
    print(f"key:{key}, val:{dic[key]}")

#Loop the dictionary value
for val in dic.values():
    print(f"val:{val}")

#dictionary key,Loop value
for key, val in dic.items():
    print(f"key:{key}, val:{val}")

The dictionary ʻitems () is much easier to come up with than the array ʻenumerate spelling: relaxed: Whether you want to loop only the key or only the value of the dictionary For the time being, I think it's okay to use ʻitems ()` to get both key and value.

List comprehension

It is used when you want to generate a new array or dictionary from an array or dictionary. With the usual method, you need to first create an empty array, then loop the original array and add elements to the new array, but with comprehension, such an operation is 1 It can be achieved with a line. It also improves performance.

list_comp.py


#Initialization of original array / dictionary
arr = [1, 2, 3, 4, 5]
dic = {"key1":1, "key2": 2, "key3": 3, "key4": 4, "key5": 5}

#Array to array(Double each array element)
conv_arr = [val * 2 for val in arr]
print(conv_arr)

#Dict from array(index to key)
conv_dic = {f"key{index + 1}": val for index, val in enumerate(arr)}
print(conv_dic)

#Array from dict(key-in the value string)
conv_arr = [f"{key}-{val}" for key, val in dic.items()]
print(conv_arr)

#From dict to dict(Capitalize key and double value)
conv_dic = {key.upper(): val * 2 for key, val in dic.items()}
print(conv_dic)

Grammatically, the case of an array [Expression for arbitrary variable name in iterable object]

In the case of dictionary {key: value for arbitrary variable name in iterable object} It will be.

List comprehension (with IF)

It is also possible to add an IF condition to the list comprehension notation and extract only the elements that meet the condition.

list_comp.py


#Initialization of the original array
arr = [1, 2, 3, 4, 5]

#Array to array(Get only even elements and multiply the elements by 10)
conv_arr = [val * 10 for val in arr if val % 2 == 0]
print(conv_arr)

We hope that this article will be of some help to you. Have a good python life!

Recommended Posts

[Python] I tried to summarize the array, dictionary generation method, loop method, list comprehension notation
Python -I tried to restore the dictionary comprehensive notation to its original form-
I tried to summarize the string operations of Python
I tried to summarize the frequently used implementation method of pytest-mock
I tried to summarize the umask command
Python3 standard input I tried to summarize
I tried to summarize the graphical modeling.
Python amateurs try to summarize the list ①
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
[Introduction to Udemy Python3 + Application] 60. List comprehension notation
A python amateur tries to summarize the list ②
LeetCode I tried to summarize the simple ones
I tried to graph the packages installed in Python
I tried to summarize how to use matplotlib of python
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to solve the problem with Python Vol.1
I tried to simulate the dollar cost averaging method
Python3 comprehension (List, dictionary) that I have seen somewhere
I compared the speed of the reference of the python in list and the reference of the dictionary comprehension made from the in list.
I tried to find the entropy of the image with python
I tried to introduce the block diagram generation tool blockdiag
I tried to simulate how the infection spreads with Python
[First COTOHA API] I tried to summarize the old story
I tried to summarize the code often used in Pandas
I tried "How to get a method decorated in Python"
[Python] I tried to visualize the follow relationship of Twitter
I tried to summarize the commands often used in business
I tried to implement the mail sending function in Python
[Machine learning] I tried to summarize the theory of Adaboost
I tried to enumerate the differences between java and python
I want to make the Dictionary type in the List unique
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
I tried to divide the file into folders with Python
I tried to summarize how to use the EPEL repository again
I tried to summarize what python strong people are doing in the competition professional neighborhood
I tried to solve the ant book beginner's edition with python
[Linux] I tried to summarize the command of resource confirmation system
I tried to touch Python (installation)
I tried to get the index of the list using the enumerate function
[Slack api + Python] I tried to summarize the methods such as status confirmation and message sending
I tried to create a list of prime numbers with python
I tried to display the video playback time (OpenCV: Python version)
Continuation: I tried to introduce the block diagram generation tool blockdiag
I tried to summarize the commands used by beginner engineers today
I tried to summarize the contents of each package saved by Python pip in one line
I tried to summarize everyone's remarks on slack with wordcloud (Python)
I tried to improve the efficiency of daily work with Python
I tried to move the ball
I tried to summarize all the Python plots used in the research by active science graduate students [Basic]
I tried to output the rpm list of SSH login destination to an Excel sheet with Python + openpyxl.
[Python] I tried to visualize the night on the Galactic Railroad with WordCloud!
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
I tried to summarize until I quit the bank and became an engineer
When I tried to run Python, it was skipped to the Microsoft Store
I tried to summarize the general flow up to service creation by self-education.
[Python] I tried to analyze the pitcher who achieved no hit no run
I tried to get the authentication code of Qiita API with Python.
I tried to summarize various sentences using the automatic summarization API "summpy"
(Python) I tried to analyze 1 million hands ~ I tried to estimate the number of AA ~