Info:
-------
For the complete course details, projects and questions, please reach here:
Email: letscodeinst@gmail.com
Profile: https://sterling.universitytutor.com/...
Code - List Comprehension:
--------------------------------------------
#!/usr/bin/python
Constructing a list of numbers from 1 - 10
numberList = []
for i in range(1, 11):
numberList.append(i)
print ("List of numbers: ")
print (numberList)
numberListComprehension = [i for i in range(1,11)]
print (numberListComprehension)
Constructing a list of even numbers from 2 - 10
evenNumbersList = []
for i in range(1, 11):
if i % 2 == 0:
evenNumbersList.append(i)
print ("Even numbers through regular method: ")
print (evenNumbersList)
evenNumbersListComprehension = [i for i in range(1,11) if i%2 == 0]
print (evenNumbersListComprehension)
Constructing a list of odd numbers from 1 - 9
oddNumbersList = []
for i in range(1,11):
if i % 2 != 0:
oddNumbersList.append(i)
print ("Odd numbers through regular method: ")
print (oddNumbersList)
oddNumbersListComprehension = [i for i in range(1,11) if i%2 != 0]
print (oddNumbersListComprehension)
Constructing a list of tuples
classInfoList = []
studentNames = ['John', 'Mary', 'Nathan', 'Adam', 'Bob']
studentAges = [10, 9, 10, 11, 8]
for i in range(0, 5):
studentInfo = (studentNames[i], studentAges[i])
classInfoList.append(studentInfo)
print ("List of tuples: ")
print (classInfoList)
classInfoListComprehension = [(studentNames[i], studentAges[i]) for i in range(0,5)]
print (classInfoListComprehension)
Slide - List Comprehension:
--------------------------------------------
Concise way to create lists
Returns a list and can be:
List of singleton elements
List of tuples
List of dictionaries and so on
Syntax:
Square brackets
One or more FOR clause
One or more expressions to evaluate
Variables to be added to the list
Sur cette page du site, vous pouvez voir la vidéo en ligne Python Tutorials - List Comprehension durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Lets Code 29 décembre 2018, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 21 fois et il a aimé 0 téléspectateurs. Bon visionnage!