Python has a notation called comprehension. Comprehension is synonymous with list comprehension.
There are three types, but I will explain from the list comprehension. A syntax that uses list objects and loops to generate a new list. It's a unique syntax not found in other languages, but once you get used to it, it's very convenient and very fast.
Basic way of writing comprehension [Expression for variable in sequence]
When not using list comprehension
num_list = [1, 2, 3, 4, 5] number_list = [] for num in num_list: > new_num = num * 2 > number_list.append(new_num) print(number_list)
[2, 4, 6, 8, 10]
When using list comprehension notation
num_list = [1, 2, 3, 4, 5] number_list = [num * 2 for num in num_list ] print(number_list)
[2, 4, 6, 8, 10]
The point is that by using list comprehensions, you can make the description short and cohesive.
It is also possible to use an if statement by writing as follows.
[Conditions for expressions for variables in sequences if list elements]
num = “1, 2, 3, 4, a,5" number = [int(s) for s in num.split() if s.isdigit()] print(number)
[1, 2, 3, 4, 5]
Dictionary comprehension notation
As with list comprehensions, dictionary-type elements can be processed together. The usage is the same as the list comprehension notation.
Basic way of writing comprehension {Key: for variable in sequence (if condition)}
subject = {‘kokugo’: 75, ‘suugaku’: 64, ‘eigo’: 92} num = {point: str (n) + ‘point’ for point, n in subject.items ()} print(num) {‘Kokugo’: 75 points, ‘suugaku’: 64 points, ‘eigo’: 92 points}
Set comprehension Also called set comprehension
Basic way to write set comprehension {Expression for variable in sequence (if condition)}
num_set = {number for number in range(19) if number % 3 == 0} print(num_set) {0, 3, 6, 9, 12, 15, 18}
The interface used to access the elements of a set quarterly, which is there to use the collection repeatedly. There are multiple types, such as lists, sets, and maps, but iterators are a mechanism for accessing them. For example, in java, we take the Set # iterator method Iterator and get the elements in order, but in Pythson we use an iterator object. Iterators can be used to describe access to an element. In the Python for statement, iterable is taken as a range, and iterator is implicitly used, which is sometimes called an internal iterator.
※interface A device or software that enables communication and control by connecting different devices / devices with a computer.
※collection An object that handles multiple elements, such as a list or Set.
Recommended Posts