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 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]
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'}
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')
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