Skip to content

Latest commit

 

History

History
101 lines (68 loc) · 2.19 KB

Object.md

File metadata and controls

101 lines (68 loc) · 2.19 KB

← back to Main Page

Objects


Comprehensions

The Compact ways to generate Data Structures using Iterators.

List Comprehension

[expression for items in iterables]
[expression for items in iterables if condition]
  • Example
mylist = [i for i in range(2,8)]
mylist#[2, 3, 4, 5, 6, 7]

mylist = [i+1 for i in range(2,8)]
mylist#[3, 4, 5, 6, 7, 8]

mylist = [i for i in range(2, 8) if i % 2 != 0]
mylist#[3,5,7]

mylist = ['a', 'b', 'c']
xylist = [1, 2]
ids = [(i, j) for i in mylist for j in xylist]#generate a list of tuples
for i, j in ids:#Unpacking a tuple!
    print(i, j)

Dictionary Comprehension

{ key_exp : val_exp for expression in iterables}
{ key_exp : val_exp for expression in iterables if condition}
  • Example
{i : i**2 for i in range(1,6)}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

{i : i**2 for i in range(1,6) if i < 4}
{1: 1, 2: 4, 3: 9}
  • Advanced Version
aa = [{'a': 1, 'b': 34, 'c': 556},
      {'a': 3, 'b': 5, 'c': 7},
      {'a': 2, 'b': 3, 'c': 8},
     ]

bb = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


[dict(item, **{'body': item['a']*5, 'title': item['b']*5})\
           for item in aa]


[{'a': 1, 'b': 34, 'body': 5, 'c': 556, 'title': 170},
 {'a': 3, 'b': 5, 'body': 15, 'c': 7, 'title': 25},
 {'a': 2, 'b': 3, 'body': 10, 'c': 8, 'title': 15}]

Set Comprehension

{expression for expression in itreables}
{expression for expression in itreables if condition}
  • Example
words = "python"
{i for i in words if i != "p"}
{'t', 'o', 'h', 'n', 'y'}

Generator Comprehensions(NOT TUPLE COMPREHENSIONS!)

(expression for expression in itreables)
(expression for expression in itreables if condition)

This returns a Generator object.Go to "Generators"

↑ Up to the Top

← back to Main Page