Extracting values from a list Python

In Python, you can generate a new list by extracting, removing, replacing, or converting elements that meet the conditions of an existing list with list comprehensions.

This article describes the following contents.

  • Basics of list comprehensions
  • Apply operation to all elements of the list
  • Extract/remove elements that meet the conditions from the list
  • Replace/convert elements that meet the conditions in the list

See the following article for examples of lists of strings.

It is also possible to randomly sample elements from a list.

  • Random sampling from a list in Python [random.choice, sample, choices]

Take the following list as an example.

l = list[range[-5, 6]] print[l] # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]

source: list_select_replace.py

Basics of list comprehensions

In Python, you can create a list using list comprehensions. It's simpler than using the for loop.

[expression for variable_name in iterable if condition]

expression is applied to the elements that satisfy condition of iterable [list, tuple, etc.], and a new list is generated. if condition can be omitted, if omitted, expression is applied to all elements.

See the following article for details on list comprehensions.

  • List comprehensions in Python

Apply operation to all elements of the list

If you write the desired operation in the expression part of list comprehensions, that operation is applied to all the elements of the list.

l_square = [i**2 for i in l] print[l_square] # [25, 16, 9, 4, 1, 0, 1, 4, 9, 16, 25] l_str = [str[i] for i in l] print[l_str] # ['-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5']

source: list_select_replace.py

You can use this to convert a list of numbers to a list of strings. See the following article for details.

  • Convert a list of strings and a list of numbers to each other in Python

If you just want to select elements by condition, you do not need to process them with expression, so you can write it as follows.

[variable_name for variable_name in original_list if condition]

Only the elements that meet the conditions [elements that return True for condition] are extracted, and a new list is generated.

l_even = [i for i in l if i % 2 == 0] print[l_even] # [-4, -2, 0, 2, 4] l_minus = [i for i in l if i 0 else i for i in l] print[l_replace] # [-5, -4, -3, -2, -1, 0, 100, 100, 100, 100, 100] l_replace2 = [100 if i > 0 else 0 for i in l] print[l_replace2] # [0, 0, 0, 0, 0, 0, 100, 100, 100, 100, 100] l_convert = [i * 10 if i % 2 == 0 else i for i in l] print[l_convert] # [-5, -40, -3, -20, -1, 0, 1, 20, 3, 40, 5] l_convert2 = [i * 10 if i % 2 == 0 else i / 10 for i in l] print[l_convert2] # [-0.5, -40, -0.3, -20, -0.1, 0, 0.1, 20, 0.3, 40, 0.5]

source: list_select_replace.py

  • English / Japanese
  • |
  • Disclaimer
  • Privacy policy
  • GitHub
  • © 2017 nkmk.me

Video liên quan

Chủ Đề