This is a memo of O'Reilly Japan's book effective python. https://www.oreilly.co.jp/books/9784873117560/ P21~23
** Extract the name with the longest number of characters **
names = ['Cecilia', 'Lise', 'Marie' ]
letters = [len(n) for n in names]
longest_name = None
max_letters = 0
#Pattern 1
for i in range(len(names)):
count = letters[i]
if count > max_letters:
longest_name = names[i]
max_letters = count
print(longest_name)
>>>
Cecilia
There is no syntactic problem, but it is hard to see that it is accessed twice with the subscript of the list. Also, if the list is extremely long, it is not ecological to expand all the contents, so I would like to solve it with a generator.
for name, count in zip(names, letters): #Note the size of the zip element
if count > max_letters:
longest_name = name
maxx_letters = count
print(longest_name)
>>>
Cecilia
If you use zip (), the list of contents is returned in parallel by the generator, so it is a memory-friendly specification. Also, it is easier to see than anything else.
However, if the elements in the zip do not match. Note that the whole thing will end when the shorter iterator runs out.
Recommended Posts