Python 学习笔记(一)Data type

Data types:

Sequence types: (有序的类型)

  • strings
  • tuples
  • lists

Immutable types: (不可变的类型)

  • numbers
  • strings
  • tuples

#String:

text = "Lists and Strings can be accessed via indices!"

String 的几种表示法:

• Single quotes: 'spa"m'
• Double quotes: "spa'm"
• Triple quotes: '''... spam ...''', """... spam ..."""
• Escape sequences: "s\tp\na\0m"
• Raw strings: r"C:\new\test.spm"

>>> mantra = """Always look
... on the bright
... side of life."""
>>>
>>> mantra
'Always look\n on the bright\nside of life.'

>>> print(mantra)
Always look
on the bright
side of life.

反转字符串

>>> S = 'hello'
>>> S[::−1]
'olleh'

str and repr: (convert number to string)

>>> print(str('b'),repr('a'))
b 'a'
>>> print(str('42'),repr('42'))
42 '42'
>>> print(str("42"),repr("42"))
42 '42'

character to ASCII:

>>> ord('s')
115
>>> chr(115)
's'

如何改变String :

>>> S = S + 'SPAM!' # To change a string, make a new one
>>> S
'spamSPAM!'

>>> S = 'splot'
>>> S = S.replace('pl', 'pamal')
>>> S
'spamalot'

Format:

>>> 'That is %d %s bird!' % (1, 'dead') # Format expression
That is 1 dead bird!
>>> 'That is {0} {1} bird!'.format(1, 'dead') # Format method in 2.6 and 3.0
'That is 1 dead bird!'

#List []

L = ["London", "Paris", "Strasbourg", "Zurich"]

 The main properties of Python lists:

  • They are ordered
  • The contain arbitrary objects
  • Elements of a list can be accessed by an index
  • They are arbitrarily nestable, i.e. they can contain other lists as sublists
  • Variable size
  • They mutable, i.e. they elements of a list can be changed

  简单的copy会改变原来list的值,如果不想改变原来的值,则需要深度copy (deepcopy):

>>> lst1 = ['a','b',['ab','ba']]
>>> lst2 = lst1[:]
>>> lst2[0] = 'c'
>>> lst2[2][1] = 'd'
>>> print(lst1)
['a', 'b', ['ab', 'd']]

  Deepcopy:

>>> from copy import deepcopy
>>> lst1 = ['a','b',['ab','ba']]
>>> lst2 = deepcopy(lst1)
>>> lst2[2][1] = "d"
>>> lst2[0] = "c"
>>> print(lst2)
['c', 'b', ['ab', 'd']]
>>> print(lst1)
['a', 'b', ['ab', 'ba']]

string to list:

>>> S = 'spammy'
>>> L = list(S)
>>> L
['s', 'p', 'a', 'm', 'm', 'y']

Operation:

>>> s = "Test List"
>>> l = list(s)
>>> l
['T', 'e', 's', 't', ' ', 'L', 'i', 's', 't']
>>> l.append('h')
>>> l
['T', 'e', 's', 't', ' ', 'L', 'i', 's', 't', 'h']
>>> l.extend(['a','b'])
>>> l
['T', 'e', 's', 't', ' ', 'L', 'i', 's', 't', 'h', 'a', 'b']
>>> l.insert(2,'c')
>>> l
['T', 'e', 'c', 's', 't', ' ', 'L', 'i', 's', 't', 'h', 'a', 'b']
>>> del l[2]
>>> l
['T', 'e', 's', 't', ' ', 'L', 'i', 's', 't', 'h', 'a', 'b']
>>> l.remove('t')
>>> l
['T', 'e', 's', ' ', 'L', 'i', 's', 't', 'h', 'a', 'b']

#remove all matched characters
>>> for i in l:
    if i =='s':
        l.remove(i)

        
>>> l
['T', 'e', ' ', 'L', 'i', 'h', 'a', 'b']
>>> L = [x**2 for x in range(5)]
>>> L
[0, 1, 4, 9, 16]

排序:

>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort() # Sort with mixed case
>>> L
['ABD', 'aBe', 'abc']
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort(key=str.lower) # Normalize to lowercase
>>> L
['abc', 'ABD', 'aBe']
>>>
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort(key=str.lower, reverse=True) # Change sort order
>>> L
['aBe', 'ABD', 'abc']

#Tuple ()

tup1 = ('physics', 'chemistry', 1997, 2000);

  A tuple is an immutable list: 

  • Tuples are faster than lists.
  • If you know, that some data doesn't have to be changed, you should use tuples instead of lists, because this protect your data against accidental changes to these data.
  • Tuples can be used as keys in dictionaries, while lists can't.

  Tuple 语法:Commas and parentheses

>>> x = (40) # An integer!
>>> x
40
>>> y = (40,) # A tuple containing an integer
>>> y
(40,)

Tuple to list:

>>> T = (1, 2, 3, 4, 5)
>>> L = [x + 20 for x in T]
>>> L
[21, 22, 23, 24, 25]

>>> T = (1, 2, 3, 2, 4, 2)
>>> T.index(2,3) #从index3开始找2
3

tuple immutability applies only to the top level of the ruple itself.

>>> T = (1, [2, 3], 4)
>>> T[1] = 'spam' # This fails: can't change tuple itself
TypeError: object doesn't support item assignment
>>> T[1][0] = 'spam' # This works: can change mutables inside
>>> T
(1, ['spam', 3], 4)

#Set {}

  • an unordered collection
  • unique value
  • like keys of valuesless dictionary, but supports extra operations

Can use to remove duplicates:

>>> L = [1, 2, 1, 3, 2, 4, 5]
>>> set(L)
{1, 2, 3, 4, 5}
>>> L = list(set(L)) # Remove duplicates
>>> L
[1, 2, 3, 4, 5]

Extra operations:

>>> engineers = {'bob', 'sue', 'ann', 'vic'}
>>> managers = {'tom', 'sue'}
>>> engineers & managers
{'sue'}
>>> engineers | managers
{'ann', 'tom', 'bob', 'vic', 'sue'}
>>> engineers - managers
{'ann', 'vic', 'bob'}
>>> managers ^ engineers # Who is in one but not both?
{'ann', 'tom', 'vic', 'bob'}

#Dictionary {key:value}

  • Sequence operations don’t work.
  • Keys need not always be strings.
  • Assigning to new indexes adds entries.
>>> food = {"ham" : "yes", "egg" : "yes", "spam" : "no" }
>>> D = {'spam': 2, 'ham': 1, 'eggs': 3}
>>> list(D.values())
[3, 1, 2]
>>> list(D.items())
[('eggs', 3), ('ham', 1), ('spam', 2)]

Using dictionaries as 'records':

>>> mel = {'name': 'Mark',
       'jobs': ['trainer', 'writer'],
       'web': 'www.rmi.net/˜lutz',
       'home': {'state': 'CO', 'zip':80513}}
>>> mel['jobs']
['trainer', 'writer']
>>> mel['jobs'][1]
'writer'
>>> mel['home']['zip']
80513

Ways to make dictionaries:

{'name': 'mel', 'age': 45} # Traditional literal expression
D = {} # Assign by keys dynamically
D['name'] = 'mel'
D['age'] = 45
dict(name='mel', age=45) # dict keyword argument form
dict([('name', 'mel'), ('age', 45)]) # dict key/value tuples form

>>> dict.fromkeys(['a', 'b'], 0)
{'a': 0, 'b': 0}

Turn list to dictionary:

>>> list(zip(['a', 'b', 'c'], [1, 2, 3])) # Zip together keys and values
[('a', 1), ('b', 2), ('c', 3)]
>>> D = dict(zip(['a', 'b', 'c'], [1, 2, 3])) # Make a dict from zip result
>>> D
{'a': 1, 'c': 3, 'b': 2}

#new method in 3.0

>>> D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])}
>>> D
{'a': 1, 'c': 3, 'b': 2}

>>> D = {c.lower(): c + '!' for c in ['SPAM', 'EGGS', 'HAM']}
>>> D
{'eggs': 'EGGS!', 'ham': 'HAM!', 'spam': 'SPAM!'}

Sort:

>>> D
{'a': 1, 'c': 3, 'b': 2} # Better yet, sort the dict directly
>>> for k in sorted(D): print(k, D[k]) # dict iterators return keys
...
a 1
b 2
c 3

原文地址:https://www.cnblogs.com/zyf7630/p/3069353.html