Python Bytes: List Comprehensions with Conditionals

Опубликовано: 14 Май 2021
на канале: CyberScribe.org
89
3

Python Bytes
Intermediate Python Topics
List Comprehensions with Conditionals

#A method of making lists from other values.

#Defining a list and its contents at the same time.

new_list = [ item for item in iterable ]

new_list = [ item for item in iterable if conditional]

#An 'iterable' is an object that contains other objects within it.
#Lists, Dictionaries, Tuples, Sets, range(), and more.

#You can work backwards from a loop to create the comprehension and understand the logic.
#This is a good technique when you are still new to list comprehensions.

#Review:
fqdns = ['abc.dev.com', 'dew.qka.com', 'kwlan.ewa.com']
hostnames = list()
for fqdn in fqdns:
hostnames.append(fqdn.split('.')[0])

hostnames2 = [ fqdn.split('.')[0] for fqdn in fqdns ]

print(hostnames)
print(hostnames2)

#You can also use a conditional statement at the end to filter values

if you only want hostnames with 'kw' in the hostname...
hostnames3 = [ fqdn.split('.')[0] for fqdn in fqdns if 'kw' in fqdn.split('.')[0]]

#Example 1:
#Working with another list and filtering values
performance counter for a script over time, you want to get all values over 3
counter = [1, 2, 5, 2, 3, 1, 6, 3, 7, 11, 2, 9, 2, 3, 1, 33, 3, 1, 5, 2, 5, 1, 3, 6, 3, 1, 2, 3, 4, 1, 4]
high_counter = list()
for num in counter:
if num (greater than symbol) 3:
high_counter.append(num)

high_counter2 = [num for num in counter if num (greater than symbol) 3]

print(sorted(high_counter))
print(sorted(high_counter2))

#Example 2:
#Working with a dictionary and filtering values
pull out the names of employees who are in the admins group

employee_info = [
{"name": "Sally", "title": "Marketing", "groups":["marketing", "leadership"]},
{"name": "Bob", "title": "Customer Service", "groups":["marketing", "customer service"]},
{"name": "Phil", "title": "Developer", "groups":["it", "development", "admin"]},
{"name": "Kelly", "title": "Accounting", "groups":["leadership", "accounting"]},
{"name": "Dan", "title": "DBA", "groups":["it", "admin", "database"]}
]

emp_info = list()
for employee in employee_info:
if 'admin' in employee['groups']:
emp_info.append(employee['name'])

emp_info2 = [employee['name'] for employee in employee_info if 'admin' in employee['groups']]

print(emp_info)
print(emp_info2)

#Example 3:
employee_info = {
"Sally": {"title": "Marketing", "groups":["marketing", "leadership"]},
"Bob": {"title": "Customer Service", "groups": ["marketing", "customer service"]},
"Phil": {"title": "Developer", "groups": ["it", "development", "admin"]},
"Kelly": {"title": "Accounting", "groups": ["leadership", "accounting"]},
"Dan": {"title": "DBA", "groups": ["it", "admin", "database"]}
}

emp_admins = list()
for employee in employee_info:
if 'admin' in employee_info[employee]['groups']:
emp_admins.append(employee)

emp_admins2 = [employee for employee in employee_info if 'admin' in employee_info[employee]['groups']]

print(emp_admins)
print(emp_admins2)


Смотрите видео Python Bytes: List Comprehensions with Conditionals онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь CyberScribe.org 14 Май 2021, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 8 раз и оно понравилось людям.