본문 바로가기
Study(매일매일한걸음씩)/Python

[Study] Python, eval,lamda,map

by 여유러운백수삶개발자 2023. 2. 1.
공부하다가 몰라서 정리
1. eval(쉽게 이야기 하면 문자나 숫자로 구성된 문자를 파이션 표현식으로 바꾼다(산술식)
하지만 사용하기 매우 조심해야 한다.

eval is a built-in function in Python that evaluates a string as a Python expression. The expression can be a simple value, such as a string or a number, or a more complex expression, such as an arithmetic expression.

For example, the following code will evaluate the string "2 + 3" as a Python expression and print the result:

expression = "2 + 3"
result = eval(expression)
print(result) # Output: 5

In this example, the string "2 + 3" is passed to the eval function as an argument, which evaluates the expression and returns the result, 5.

It's important to note that the eval function can be dangerous to use as it evaluates any valid Python expression, including potentially harmful code. It's only recommended to use eval on trusted input, and to avoid using it with untrusted or user-generated data.

x = 5
expression = "x * 2"
result = eval(expression)
print(result) # Output: 10
expression = "2 ** 3"
result = eval(expression)
print(result) # Output: 8
lamda(함수와 비슷하나 간단하게 사용가능하고, 익명성이 가능하며, 가독성이 좋다)

In Python, lambda is a keyword used to create small, anonymous functions. lambda functions are defined using the lambda keyword followed by a list of arguments, a colon, and the expression that should be executed when the function is called.

add = lambda x, y: x + y
result = add(2, 3)
print(result) # Output: 5

In this example, a lambda function that takes two arguments, x and y, and returns their sum is defined. The function is assigned to the variable add, which can be used to call the function and obtain its result.

squared = lambda x: x ** 2
result = squared(5)
print(result) # Output: 25

In this example, a lambda function that takes one argument, x, and returns the square of x is defined. The function is assigned to the variable squared, which can be used to call the function and obtain its result.

lambda functions are used in Python for the following reasons:
  1. Compactness: lambda functions are small, anonymous functions that can be defined inline, making it easier to write simple, one-line functions.
  2. Readability: lambda functions can improve code readability by making it easier to write simple functions that are self-contained and have a clear purpose.
  3. Ease of use: lambda functions can be used as arguments to other functions, allowing for functional programming constructs such as map, filter, and reduce.
  4. Improved performance: lambda functions are often faster than defining a function using def because they are not bound to a name and therefore do not require a full function definition.

It's important to note that lambda functions are limited in their functionality, and are best suited for simple functions. If your function is complex or requires multiple lines of code, it's usually better to define a regular function using def instead of a lambda function.

map
리스트에서 for 대신 강력하게 사용이 가능하다,  

In Python, the map function is used to apply a given function to each element of an iterable object, such as a list or a tuple, and returns a map object containing the results.

Here's an example of using map to square all elements in a list:

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]

In this example, the map function is used to apply the lambda function lambda x: x**2 to each element of the list numbers. The result of the map function is then converted to a list and assigned to the variable squared_numbers.

The map function can be useful when you need to apply a simple operation to each element of an iterable, without having to write a for loop or a list comprehension. It's especially useful when used in combination with lambda functions to perform complex operations with concise, readable code. 

words = ['apple', 'banana', 'cherry']
word_lengths = list(map(len, words))
print(word_lengths) # Output: [5, 6, 6]

In this example, the map function is used to apply the len function to each element of the list words. The result of the map function is then converted to a list and assigned to the variable word_lengths

numbers1 = [1, 2, 3, 4, 5]
numbers2 = [10, 20, 30, 40, 50]
product = list(map(lambda x, y: x * y, numbers1, numbers2))
print(product) # Output: [10, 40, 90, 160, 250]

In this example, the map function is used to apply the lambda function lambda x, y: x * y to corresponding elements from each of the lists numbers1 and numbers2. The result of the map function is then converted to a list and assigned to the variable product.

The map function is used in Python for the following reasons:
  1. Simplicity: map provides a simple and concise way to apply a function to each element of an iterable, without having to write a for loop or a list comprehension.
  2. Readability: map can make your code more readable by breaking down complex operations into simple, manageable steps.
  3. Reusability: map allows you to encapsulate a function in a single line of code, making it easy to reuse and apply to different iterables.
  4. Performance: map is generally faster than using a for loop or a list comprehension, especially when used with built-in functions such as len or str.
  5. Flexibility: map can be used with multiple iterables of the same length, making it easy to apply a function to corresponding elements from each iterable.

map is particularly useful when you need to apply a simple operation to each element of an iterable, without having to write a for loop or a list comprehension. It can also be used in functional programming constructs, such as filter and reduce, to perform more complex operations with concise, readable code.

댓글