Kinh Nghiệm về Python double list comprehension with if Mới nhất Chi Tiết

You đang tìm kiếm từ khóa Python double list comprehension with if Mới nhất được Update vào lúc : 2022-12-09 09:05:00 . Với phương châm chia sẻ Bí quyết Hướng dẫn trong nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi đọc tài liệu vẫn ko hiểu thì hoàn toàn có thể lại Comments ở cuối bài để Ad lý giải và hướng dẫn lại nha.

Pro đang tìm kiếm từ khóa Python double list comprehension with if được Cập Nhật vào lúc : 2022-12-09 09:05:13 . Với phương châm chia sẻ Bí kíp Hướng dẫn trong nội dung nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi tìm hiểu thêm nội dung nội dung bài viết vẫn ko hiểu thì hoàn toàn hoàn toàn có thể lại phản hồi ở cuối bài để Mình lý giải và hướng dẫn lại nha.

Introduction
Whats the Difference between List Comprehension and For Loop in Python?
Example 1: Using For loop to Iterate through a String
Example 2: Using List Comprehension to Iterate through a String
Syntax of List Comprehension
List Comprehensions vs Lambda functions
Example 3: Using Lambda functions inside List
Conditionals in List Comprehension
Example 4: Using if with List Comprehension
Example 5: Nested if with List Comprehension
Example 6: ifelse With List Comprehension
Nested Loops in List Comprehension
Example 7: Finding Transpose of Matrix using Nested Loops
Example 8: Finding Transpose of a Matrix using List Comprehension
Key Points on List Comprehension
More Examples of List Comprehensions
Example 9: Finding the elements in a list in which elements are ended with the letter b and the length of that element is greater than 2
Example 10: Reverse each String in a Tuple

Introduction

In this article, well study Python list comprehensions, and the way to use them.The topics which well be discussing in this article are as follows:

    Whats the difference between List Comprehension and For loop in Python?
    Syntax of List Comprehensions in python
    Difference between Lambda functions and List Comprehensions
    Conditionals within the List Comprehension
    Nested loops within the List Comprehensions in python
    Key points on List Comprehension
    More Examples of List Comprehension

Image Source: Google Images

Whats the Difference between List Comprehension and For Loop in Python?

Suppose, we wish to separate the letters of the word analytics and add the letters as items of a list. The primary thing that comes to mind would be using for loop.

Example 1: Using For loop to Iterate through a String

separated_letters = []

for letter in ‘analytics’:

separated_letters.append(letter)

print(separated_letters)

Output:

[ ‘a’, ‘n’, ‘a’, ‘l’, ‘y’, ‘t’, ‘i’, ‘c’, ‘s’ ]

Code Explanation:

In this example, we will split the string based on characters and store all those characters in a new list.

However, Python has a better way to solve this issue using List Comprehension. List comprehension is a sublime way to define and make lists based on existing lists.

Lets see how the above program may be written using list comprehensions.

Example 2: Using List Comprehension to Iterate through a String

separated_letters = [ letter for letter in ‘analytics’ ]

print( separated_letters)

Output:

[ ‘a’, ‘n’, ‘a’, ‘l’, ‘y’, ‘t’, ‘i’, ‘c’, ‘s’ ]

Code Explanation:

In the above example, a brand new list is assigned to variable separated_letters, and the list contains the things of the iterable string analytics. Finally, to receive the output, we call the print() function of Python.

Syntax of List Comprehension

[expression for item in list]

Now, we are able to identify where list comprehensions are used.

If you noticed, analytics could be a string, not a list. This is often the facility of list comprehension. It can identify when it receives a string or a tuple and works on that as a list.

You can try this using loops. However, not every loop may be rewritten as a list comprehension. But as you learn and acquire comfortable with list comprehensions, Youll end up replacing more and more loops with this elegant syntax.

List Comprehensions vs Lambda functions

To work or operations with the lists, List comprehensions arent the only way but various built-in functions and lambda functions can create and modify lists in fewer lines of code.

Example 3: Using Lambda functions inside List

letters = list(map(lambda y: y, ‘analytics’))

print(letters)

Output:

[ ‘a’, ‘n’, ‘a’, ‘l’, ‘y’, ‘t’, ‘i’, ‘c’, ‘s’ ]

Code Explanation:

In this code, we will separate the characters of the string using lambda functions.

However, in general list comprehensions are more human-readable than lambda functions. Its easier to grasp what the programmer was trying to accomplish when list comprehensions are used.

Conditionals in List Comprehension

List comprehensions can utilize conditional statements to change the existing lists (or other tuples). we are going to create a list that uses mathematical operators, integers, and range().

Example 4: Using if with List Comprehension

even_list = [ i for i in range(10) if i % 2 == 0]

print(even_list)

Output:

[0, 2, 4, 6, 8]

Code Explanation:

The list, even_list, is going to be populated by the things in the range from 0 9 if the items value is divisible by 2.

Example 5: Nested if with List Comprehension

filtered_list = [ x for x in range(50) if x % 2 == 0 if x % 5 == 0]

print(filtered_list)

Output:

[0, 10, 20, 30, 40]

Code Explanation:

Here, list comprehension checks:

Is x divisible by 2 or not?

Is x divisible by 5 or not?

If x satisfies both conditions, x is appended to filtered_list.

Example 6: ifelse With List Comprehension

list = [“even” if y%2==0 else “odd” for y in range(5)]

print(list)

Output:

[‘even’, ‘odd’, ‘even’, ‘odd’, ‘even’]

Code Explanation:

Here, list comprehension will check the five numbers from 0 to 4. If y is divisible by 2, then even is appended to the obj list. If not, odd is appended.

Nested Loops in List Comprehension

Suppose, wed like to compute the transpose of a matrix that needs nested for loop. Lets see how its done using normal for loop first.

Example 7: Finding Transpose of Matrix using Nested Loops

transposed_matrix = []

matrix = [[1, 2, 3, 4], [4, 5, 6, 8]]

for i in range(len(matrix[0])):

transposed_row = []

for row in matrix:

transposed_row.append(row[i])

transposed_matrix.append(transposed_row)

print(transposed_matrix)

Output:

[[1, 4], [2, 5], [3, 6], [4, 8]]

Code Explanation:

The above code uses two for loops to search out the transpose of the matrix.

Also, We can perform nested iterations inside a list comprehension. In this section, we are going to find the transpose of a matrix using a nested loop inside a list comprehension.

Example 8: Finding Transpose of a Matrix using List Comprehension

matrix = [[1, 2], [3,4], [5,6], [7,8]]

transpose_matrix = [[row[i] for row in matrix] for i in range(2)]

print (transpose_matrix)

Output:

[[1, 3, 5, 7], [2, 4, 6, 8]]

Code Explanation:

In the above program, weve got a variable matrix that has 4 rows and a couple of columns. We need to seek out the transpose of the matrix. For that, we used list comprehension.

Key Points on List Comprehension

The key points which we have to keep in mind while working with list comprehension are as follows:

    List comprehension is a sublimewayto define and build lists with the help ofexisting lists.
    In comparison to normal functions and loops, List comprehension is usually more compact and faster for creating lists.
    However, we should always avoid writing very long list comprehensions in one line to confirm that code is user-friendly.
    Remember, every list comprehension is rewritten in forloop, but every for loop cant be rewritten within the kind of list comprehension.

More Examples of List Comprehensions

Let see some more examples related to List Comprehension so that you have a better understanding of List Comprehensions in Python.

Example 9: Finding the elements in a list in which elements are ended with the letter b and the length of that element is greater than 2

names = [‘Ch’,’Dh’,’Eh’,’cb’,’Tb’,’Td’,’Chb’,’Tdb’]

final_names = [name for name in names ifname.lower().endswith(‘b’) and len(name) > 2]

final_names

Output:

[‘Chb’, ‘Tdb’]

Code Explanation:

In the above code, we use list comprehension with some conditions associated with it. The functions involved in the conditions are as follows:

    name. lower.endswith(b): This function filter out all the strings from the list that are ended with the letters b or B.
    len(name): This function finds the length of all the elements in a specified list.

Example 10: Reverse each String in a Tuple

# Reverse each elements in a specified tuple

List = [string[::-1] for string in (‘Hello’, ‘Analytics’, ‘Vidhya’)]

# Display the list

print(List)

Output:

[ ‘olleH’, ‘scitylanA’, ‘ayhdiV’ ]

Code Explanation:

In the above code, we use the concept of slicing in a string, therefore by using the str[::-1] function, we can reverse the elements of a string, and we apply this function to every element in the tuple by using list comprehension.

This ends our discussion!

End Notes

I hope you enjoyed the article.

If you want to connect with me, please feel không lấy phí to contact me byEmail.

Your suggestions and doubts are welcomed here in the comment section. Thank you for reading my article!

The truyền thông shown in this article are not owned by Analytics Vidhya and are used the Authors discretion.

Reply

8

0

Chia sẻ

Share Link Download Python double list comprehension with if miễn phí

Bạn vừa đọc tài liệu Với Một số hướng dẫn một cách rõ ràng hơn về Clip Python double list comprehension with if tiên tiến và phát triển và tăng trưởng nhất Share Link Cập nhật Python double list comprehension with if Free.

Hỏi đáp vướng mắc về Python double list comprehension with if

Nếu sau khi đọc nội dung nội dung bài viết Python double list comprehension with if vẫn chưa hiểu thì hoàn toàn hoàn toàn có thể lại Comments ở cuối bài để Admin lý giải và hướng dẫn lại nha

#Python #double #list #comprehension

4530

Review Python double list comprehension with if Mới nhất ?

Bạn vừa đọc Post Với Một số hướng dẫn một cách rõ ràng hơn về Clip Python double list comprehension with if Mới nhất tiên tiến và phát triển nhất

Share Link Tải Python double list comprehension with if Mới nhất miễn phí

Quý khách đang tìm một số trong những Chia Sẻ Link Cập nhật Python double list comprehension with if Mới nhất miễn phí.

Hỏi đáp vướng mắc về Python double list comprehension with if Mới nhất

Nếu sau khi đọc nội dung bài viết Python double list comprehension with if Mới nhất vẫn chưa hiểu thì hoàn toàn có thể lại phản hồi ở cuối bài để Tác giả lý giải và hướng dẫn lại nha
#Python #double #list #comprehension #Mới #nhất