Python Programming Learn - part 1

>>> M = [[1,2,3],
                 [4,5,6],
                 [7,8,9]]
>>> M
[[1,2,3], [4,5,6], [7,8,9]]
>>> M[1]
[4,5,6]

>>> M[1][2]
6

>>> col2 = [row[1] for row in M]
>>> col2
[2,5,8]

or

>>> for row in M:
               col2 =row[1]
               print(col2)
2
5
8
>>> for row in M:
              col2 =row[1]+2
              print(col2)
4
7
10
>>> for row in M:
               if row[1] % 2 == 0:
                    col2 = row[1]
                    print(col2)

       

2
8
>>> diag = [M[i][i] for i in [0,1,2]]
>>> diag
[1,5,9]

or

>>> for i in [0,1,2]:
             diag = M[i][i]
             print(s1)
1
5
9

Sorting Keys: for Loops

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> D
{'a': 1, 'c': 3, 'b': 2}

>>> Ks = D.keys()
>>> Ks
['a', 'c', 'b']                                          # Unordered keys list
>>> Ks.sort()
>>> Ks
['a', 'b', 'c']                                          # Sorted keys list
>>> for key in Ks:
              print (key, '=>', D[key])       # Iterate though sorted keys
a => 1
b => 2
c => 3

or

>>> D
{'a': 1, 'c': 3, 'b': 2}
>>> for key in sorted(D):
               print (key, '=>', D[key])
a => 1
b => 2
c => 3

Iteration and Optimization

>>> squares = []
>>> for x in [1, 2, 3, 4, 5]:
               squares.append(x ** 2)
>>> squares
[1, 4, 9, 16, 25]


Files

>>> f = open('data.txt', 'w')       # Make a new file in output mode
>>> f.write('I\n')                         # Write strings of bytes to it
>>> f.write('Love\n')                  # Close to flush output buffers to disk
>>> f.write('Python\n')
>>> f.close( )

>>> f = open('data.txt')             # 'r' is the default processing mode
>>> bytes = f.read( )                 # Read entire file into a string
>>> bytes
'I\nLove\nPython\n'

>>> print(bytes)
I
Love
Python

>>> bytes.split()           # File content is always a string
['I', 'Love', 'Python']


Other Core Types

>>> X = set('spam')
>>> Y = set(['h', 'a', 'm'])    # Make 2 sets out of sequences
>>> X, Y
(set(['a', 'p', 's', 'm']), set(['a', 'h', 'm']))

>>> X & Y                         # Intersection
set(['a', 'm'])

>>> X | Y                         # Union
set(['a', 'p', 's', 'h', 'm'])

>>> X – Y                         # Difference
set(['p', 's'])

SHARE

About Lasha Gogua

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment