CS231python课程——基础(列表、字典、元组、集合、函数、类)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013317445/article/details/84556718

基础

列表list

#如果想要在循环体内访问每个元素的指针,可以使用内置的enumerate函数
animals=['cat','dog','fish']
for i,animal in enumerate(animals):
    print(i+1, animal)
(1, 'cat')
(2, 'dog')
(3, 'fish')
#将列表中的每个元素变成它的平方
#出错:x^2要写成x**2
[x**2 for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#列表解析还可以包含条件
[x**2 for x in range(1,11) if x%2==0]
[4, 16, 36, 64, 100]

字典dict

d={'cat':2, 'dog':5}
d['fish']=12
d
{'cat': 2, 'dog': 5, 'fish': 12}
d.get('monkey',None)
d.get('cat')
2
for key in d:
    print(key, d[key])
('fish', 12)
('dog', 5)
('cat', 2)
for key,value in d.items():
    print(key, value)
('fish', 12)
('dog', 5)
('cat', 2)
#字典解析
fruits=['apple','banana','mango']
import random
{x:random.randint(1,100) for x in fruits}
{'apple': 26, 'banana': 51, 'mango': 89}
fruits_price=[5, 2.5, 12]
for k,v in zip(fruits, fruits_price):
    print(k,v)
print('-----------------')
print('dict+zip构造字典:')
fruits_dict=dict(zip(fruits, fruits_price))
print(fruits_dict)
for k in fruits_dict:
    print(k,fruits_dict[k])
('apple', 5)
('banana', 2.5)
('mango', 12)
-----------------
dict+zip构造字典:
{'mango': 12, 'apple': 5, 'banana': 2.5}
('mango', 12)
('apple', 5)
('banana', 2.5)

集合set

最常见的应用:去重

set([2,2,2,7,3])
{2, 3, 7}

元组tuple:不可修改的有序列表

T=(2,2,3,9,0)
T1=tuple('xgboost')
T1
('x', 'g', 'b', 'o', 'o', 's', 't')

元组和列表很相似,但有区别:
1.元组不可修改(不可变性),列表可以
2.元组可以作为字典键,列表不可以
3.元组可以作为集合的元素,列表不可以

Set={0,(1,3),[2,4]} #TypeError: unhashable type: 'list'
Set
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-42-352c26a0a498> in <module>()
----> 1 Set={0,(1,3),[2,4]} #TypeError: unhashable type: 'list'
      2 Set


TypeError: unhashable type: 'list'
Set={0,(1,3),(2,4)}
Set
{0, (1, 3), (2, 4)}
D={(1,1):'a',(2,2):'b',[3,3]:'c'}#TypeError: unhashable type: 'list'
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-41-a0a0800f0432> in <module>()
----> 1 D={(1,1):'a',(2,2):'b',[3,3]:'c'}


TypeError: unhashable type: 'list'
D={(1,1):'a',(2,2):'b',(3,3):'c'}
D
{(1, 1): 'a', (2, 2): 'b', (3, 3): 'c'}

函数

def sign(x):
    if x>0:
        return 'positive'
    elif x<0:
        return 'negative'
    else:
        return 'zero'
    
for x in [-1,0,1]:
    print(sign(x))
negative
zero
positive

可选参数

def hello(name, loud=False):
    if loud:
        print(name.upper())
    else:
        print(name)
        
hello("chen")#默认是False
hello("chen", loud=True)
chen
CHEN

class Person:
    #构造方法
    def __init__(self, name, job, pay):
        self.name= name
        self.job= job
        self.pay= pay
    #行为方法
    def lastName(self):
        return self.name.split()[-1]
    def giveRaise(self, percent):
        self.pay= self.pay*(1+percent) #加self.和不加的结果是不一样的


Chen=Person("Lynn Chen", "Data Secience", 20000)
print(Chen.lastName())
Chen.giveRaise(10)
print(Chen.pay)

Chen
220000

猜你喜欢

转载自blog.csdn.net/u013317445/article/details/84556718