Useful tricks related to list and for statements in Python

** Do the same for each element of list --map **

map.py


def add1(str):         #A function that adds a 1 character to the end of a character
      return str+'1'
    
list_str = ['a', 'b', 'c']
map(add1, list_str)
Out[3]: ['a1', 'b1', 'c1']

You can do the same by writing as follows.

map.py


map(lambda x : x+'1', list_str)

This is still the same (list comprehension notation)

map.py


[x+'1' for x in list_str]

** Extract only conditional elements --filter **

Extract only the elements with 3 characters from the list.

filter.py


list_words = ['toy', 'cat', 'dog', 'girl', 'house', 'boy']
filter(lambda x : len(x)==3, list_words)
Out[7]: ['toy', 'cat', 'dog', 'boy']

This is still the same (list comprehension notation)

map.py


[x for x in list_words if len(x)==3]

** Duplicate list and how to handle it --set **

set.py


list_words2 = ['toy', 'cat', 'dog', 'girl', 'house', 'boy', 'toy', 'toy', 'cat', 'dog']
list_words2_unique = set(list_words2)

Create a set object that eliminates duplicate elements in the list

list_words2_unique
Out[8]: set(['boy', 'toy', 'house', 'dog', 'cat', 'girl'])

You can add elements to the set object with the method "add", Adding duplicate elements does not change Changes only occur for new elements to the list

set.py


list_words2_unique.add('dog')
list_words2_unique

Out[16]:
{'boy', 'cat', 'dog', 'girl', 'house', 'toy'}

set.py


list_words2_unique.add('sheep')  #Add an element that is not in the list
list_words2_unique

Out[17]:
{'boy', 'cat', 'dog', 'girl', 'house', 'sheep', 'toy'} #Will be added

You can also use Union to union with another list.

set.py


list_words2_unique.union(['lion', 'cow', 'dog', 'cat'])

Out[18]:
{'boy', 'cat', 'cow', 'dog', 'girl', 'house', 'lion', 'sheep', 'toy'}

** I want to use serial numbers in For statements-enumerate **

How to automatically assign serial numbers with a for statement

enumerate.py


list_words = ['toy', 'cat', 'dog', 'girl', 'house', 'boy']

for i, word in enumerate(list_words): #i is a serial number and word is a list element
    print (i, word)

Out[19]: 
       (0, 'toy')
       (1, 'cat')
       (2, 'dog')
       (3, 'girl')
       (4, 'house')
       (5, 'boy')

** Two-element For statement --zip **

zip.py


list_words = ['toy', 'cat', 'dog', 'girl', 'house', 'boy']
list_number =[21, 3, 12, 5, 6, 19]

#list to num_The element of number is list in word_Contains words elements
for num, word in zip(list_number, list_words):  
    print (num, word)

Out[20]: 
    (21, 'toy')
    (3, 'cat')
    (12, 'dog')
    (5, 'girl')
    (6, 'house')
    (19, 'boy')

If you write the above enumerate in zip (forcibly), it will be as follows.

length = len(list_words)

for i, word in zip(range(length), list_words):
        print (i, word)

Recommended Posts

Useful tricks related to list and for statements in Python
[Python] How to sort dict in list and instance in list
Difference between list () and [] in Python
List method argument information for classes and modules in Python
Tips for coding short and easy to read in Python
Summary of various for statements in Python
Difference between append and + = in Python list
[Python] Organizing how to use for statements
How to use is and == in Python
How to generate permutations in Python and C ++
Import-linter was useful for layered architecture in Python
Send messages to Skype and Chatwork in Python
Try to calculate RPN in Python (for beginners)
PDF files and sites useful for learning Python 3
List of Python code to move and remember
To represent date, time, time, and seconds in Python
How to plot autocorrelation and partial autocorrelation in python
How to remove duplicate elements in Python3 list
Steps to put dlib in Python Tools for Visual Studio and have fun
Python> List> Convert relative paths to absolute paths> all_filepaths = [datas_path + fp for fp in train_filepaths]
Sorted list in Python
Filter List in Python
List find in Python
Rock-paper-scissors poi in Python for beginners (answers and explanations)
Convert timezoned date and time to Unixtime in Python2.7
[For beginners] How to use say command in python!
List of posts related to optimization by Python to docker
Implemented List and Bool in Python and SQLite3 (personal note)
List of Python libraries for data scientists and data engineers
Python netCDF4 read speed and nesting of for statements
[Python] Output battles and combinations (nesting for statements and if statements)
Preferences for playing Wave in Python PyAudio and PortAudio
Problems and countermeasures for Otsu's binarization overflow in Python
Things to note when initializing a list in Python
Write tests in Python to profile and check coverage
English-English dictionary confrontation for Python and AI related English
Python # How to check type and type for super beginners
Recursively search for files and directories in Python and output
[Python] How to output the list values in order
Small and nifty Vim Plugins useful in Python / Django
[Introduction to Python] How to write repetitive statements using for statements
Python3> slice copy / slice notation> used in for statements, etc.
Selenium-Screenshot is useful for screenshots of web pages in Python3, Selenium and Google Chrome
Differences in behavior between append () and "+ =" operators when adding data to a list in Python
Try to make it using GUI and PyQt in Python
Insert Import statements needed for Python code completion in Neovim
Python list, for statement, dictionary
[Python] It might be useful to list the data frames
[Python] Convert list to Pandas [Pandas]
Try to display various information useful for debugging with python
How to swap elements in an array in Python, and how to reverse an array.
Application to display and search local memos (diary) in Python
[Python] How to use list 1
Login to website in Python
[Python] Create a date and time list for a specified period
Search for strings in Python
[Introduction to Udemy Python3 + Application] 42. for statement, break statement, and continue statement
Sort and output the elements in the list as elements and multiples in Python.
List concatenation method in python, difference between list.extend () and “+” operator
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
A simple way to avoid multiple for loops in Python