[Introduction to Python] Let's use foreach with Python

Reference site: [Introduction to Python] Let's use foreach with Python

[Introduction to Python] Let's use foreach with Python

Foreach is a repetitive statement that is often used in scripting languages. It is very often used when you want to take the contents out of an array and process them repeatedly. When using a script language, it is often desirable to have a uniform process, so if you can master repetitive statements, workability will definitely improve.

First of all, let's write a little foreach statement in perl, which is a typical scripting language.

my @sports = ("baseball", "tennis", "soccer", "volleyball");
 
foreach my $name (@sports){
    print "$name\n"
}
 
$ perl foreach.pl 
baseball
tennis
soccer
volleyball

In the foreach statement, we access from the first of the array called sports and continue to display the elements until we reach the last element.

table of contents 1 [Let's try foreach with python](Let's try foreach with python) 2 [Tips of For statement: Master more convenient usage with the feeling of foreach](Tips of For statement: Master more convenient usage with the feeling of foreach) 2.1 [I want to display the contents of the array in reverse order](I want to display the contents of the array in reverse order) 2.2 [I want to display the contents of the array in ascending order](I want to display the contents of the array in ascending order) 2.3 [I want to display the contents of the array in descending order](I want to display the contents of the array in descending order) 2.4 [I want to know the element number](I want to know the element number)]

Let's try foreach with python

Now let's try foreach with python! That said, python doesn't actually have a function named foreach. So what to do is that the for statement takes over.

Let's write it concretely.

>>> sports = ["baseball", "tennis", "soccer", "volleyball"]
>>> for name in sports:
...  print name
... 
baseball
tennis
soccer
volleyball

In this way, you can execute repeated statements in python with almost the same description as foreach.

For statement tips: Master more convenient usage with the feeling of foreach

I want to display the contents of the array in reverse order

If you try to display the contents of the array in reverse order with the script language such as perl so far, -Repack the array in reverse order and display it. -Obtain the array number and access it from the back number, There are various methods such as, but it is troublesome. Let me give you an example that you can easily do without doing this.

>>> sports = ["baseball", "tennis", "soccer", "volleyball"]
>>> for name in reversed(sports):
...  print name
... 
volleyball
soccer
tennis
baseball

You can easily reverse the order just by adding reversed () to the array to be read in this way.

I want to display the contents of the array in ascending order

You may want to display an array of disjointed numbers in ascending order. In that case, try the following.

>>> numbers = [8, 2, 7, 4, 3]
>>> for num in sorted(numbers):
...  print num
... 
2
3
4
7
8

You can easily sort by using the sorted function like this.

I want to display the contents of the array in descending order

In the previous example, it was displayed in ascending order. However, in some cases, you may want to sort in descending order. In that case, you can write as follows.

>>> numbers = [8, 2, 7, 4, 3]
>>> for num in sorted(numbers, reverse=True):
...  print num
... 
8
7
4
3
2
>>> 

You can sort in descending order by setting the keyword reverse of the sorted function to True.

I want to know the element number

You may want to know the number of the array element you are currently accessing. In such a case, there are two methods.

・ Method using range function

>>> sports = ["baseball", "tennis", "soccer", "volleyball"]
>>> for i in range(0, len(sports)):
...  print i, sports[i]
... 
0 baseball
1 tennis
2 soccer
3 volleyball

This is a C language tic feeling. This is how to use the range function to determine the element number of the array to be accessed. It's the right way to do it, but it's a little annoying. If you want to proceed easily with foreach ticks as you learned this time, why not try the following method.

・ Method using the enumerate function

>>> sports = ["baseball", "tennis", "soccer", "volleyball"]
>>> for i, name in enumerate(sports):
...  print i, name
... 
0 baseball
1 tennis
2 soccer
3 volleyball

Unlike using the range function earlier, it would be nice to be able to write in a refreshing description without having to describe where to display the array.

I want to display two arrays together If you have two arrays and want to process them together, it is convenient to use the zip function. An example looks like this:

>>> sports = ["baseball", "tennis", "soccer", "volleyball"]
>>> people = ["Ichiro", "Nishikori", "Nakata"]
>>> for name, person in zip(sports, people):
...  print name, person
... 
baseball Ichiro
tennis Nishikori
soccer Nakata

The miso here is that even if the number of elements in the array is different, it should be processed automatically according to the shorter one.

Recommended Posts

[Introduction to Python] Let's use foreach with Python
[Introduction to Python] Let's use pandas
[Introduction to Python] Let's use pandas
[Introduction to Python] Let's use pandas
Python: How to use async with
How to use FTP with Python
[Introduction to WordCloud] Let's play with scraping ♬
[Introduction to Python] How to use class in Python?
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
[Python] Introduction to CNN with Pytorch MNIST
Let's feel like a material researcher with python [Introduction to pymatgen]
[Python] Use JSON with Python
Use DynamoDB with Python
Introduction to Python language
Introduction to OpenCV (python)-(2)
Use Python 3.8 with Anaconda
Use python with docker
[Python] Easy introduction to machine learning with python (SVM)
Introduction to Artificial Intelligence with Python 1 "Genetic Algorithm-Theory-"
Introduction to Python Let's prepare the development environment
Markov Chain Chatbot with Python + Janome (2) Introduction to Markov Chain
I want to use MATLAB feval with python
[Introduction to Udemy Python3 + Application] 23. How to use tuples
Introduction to Artificial Intelligence with Python 2 "Genetic Algorithm-Practice-"
Introduction to Tornado (1): Python web framework started with Tornado
Specify the Python executable to use with virtualenv
Introduction to formation flight with Tello edu (Python)
The easiest way to use OpenCV with python
I want to use Temporary Directory with Python2
Introduction to Python with Atom (on the way)
How to use tkinter with python in pyenv
Introduction to Generalized Linear Models (GLM) with Python
[Introduction to Udemy Python3 + Application] 9. First, print with print
Let's use def in python
Connect to BigQuery with Python
Use Trello API with python
[Introduction to Python] How to use while statements (repetitive processing)
python3: How to use bottle (2)
[Introduction to Python] How to iterate with the range function?
Let's run Excel with Python
Use Twitter API with Python
[Introduction to WordCloud] It's easy to use even with Jetson-nano ♬
[Python] How to use list 1
Connect to Wikipedia with Python
Post to slack with Python 3
Use TUN / TAP with Python
An introduction to Python distributed parallel processing with Ray
Introduction to Mathematics Starting with Python Study Memo Vol.1
Reading Note: An Introduction to Data Analysis with Python
Introduction to RDB with sqlalchemy Ⅰ
How to use python interactive mode with git bash
How to use Python argparse
Introduction to serial communication [Python]
[Chapter 3] Introduction to Python with 100 knocks of language processing
Python: How to use pydub
[Python] How to use checkio
Let's write python with cinema4d.
Specify MinGW as the compiler to use with Python
Switch python to 2.7 with alternatives
Write to csv with Python
[Chapter 2] Introduction to Python with 100 knocks of language processing