Python基础笔记

在字典中删除一个元素:del knights["Dalahad"]
set去重,如:a=[1,1,3,2,4,4],a=set(a) a=[1,2,3,4]
union(联合), intersection(交), difference(差)和sysmmetricdifference(对称差集)如:
def run():
    set1 = set([4, 6, 7, 9])
    set2 = set([10, 12, 20])
    return set1.union(set2)


python 随机数
>>>import random


1、random.random


      random.random()用于生成一个0到1的随机符小数: 0 <= n < 1.0


>>> random.random()        # Random float x,


2、random.uniform


random.uniform的函数原型为:random.uniform(a, b),用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: a <= n <= b。如果 a <b, 则 b <= n <= a。


>>> random.uniform(1, 10)  # Random float x,


3、random.randint


random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b


>>> random.randint(10, 100)


4、random.randrange


random.randrange的函数原型为:random.randrange([start], stop[, step]),从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。


随机选取0到100间的偶数: 
>>> import random 
>>> random.randrange(0, 101, 2)


5、random.choice


random.choice从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。


>>> random.choice('abcdefg&#%^*f')  #随机字符 
'd'


>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] ) #随机选取字符串: 
'lemon'


6、random.shuffle


       random.shuffle的函数原型为:random.shuffle(x[, random]),用于将一个列表中的元素打乱。如:


p = ["Python", "is", "powerful", "simple", "and so on..."]  
random.shuffle(p)  
print p  
#结果(因为随机,所以你的结果可能不一样。)  
#['powerful', 'simple', 'is', 'Python', 'and so on...']  
p = ["Python", "is", "powerful", "simple", "and so on..."]


7、random.sample


random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。 如果k大于sequence元素个数的话会报错。 


参考资料:http://docs.python.org/library/random.html
Python数组定义
Python中没有数组的数据结构,但列表很像数组,如:
a=[0,1,2],这时a[0]=0, a[1]=1, a[[2]=2,但引出一个问题,即如果数组a想定义为0到999怎么办?这时可能通过a = range(0, 1000)实现。或省略为a = range(1000).如果想定义1000长度的a,初始值全为0,则 a = [0 for x in range(0, 1000)]
下面是二维数组的定义:
直接定义 a=[[1,1],[1,1]],这里定义了一个2*2的,且初始为0的二维数组。
间接定义 a=[[0 for x in range(10)] for y in range(10)],这里定义了10*10初始为0的二维数组。
还有更简单的字义二维数组的方法:
b = [[0]*10]*10,定义10*10初始为0的二维数组。
与a=[[0 for x in range(10)] for y in range(10)]比较:print a==b的结果为True。
但用b的定义方法代替a后,以前的可以正常运行的程序也出错了,经过仔细分析得出区别:
a[0][0]=1时,只有a[0][0]为1,其他全为0。
b[0][0]=1时,a[0][0],a[1][0],只到a[9,0]全部为1。
由此得到大数组中的10个小的一维数据全是一个相同的引用,即指向同一地址。
故 b = [[0]*10]*10并不符合我们常规意义上的二维数组。
同时经过试验:c=[0]*10的定义与c=[0 for x in range(10)]有同样的效果,而没有上面相同引用的问题,估计数组c的定义时是值类型相乘,而前面b的用类型的相乘,因为一维数组是一个引用(借用C#中的值类型和引用类型,不知是否合适)


id()看内存地址




parrot = "Norwegian Blue"
len(parrot) gets the length of a string!
parrot.lower()make the string all lower-case!
parrot.upper() make the string all upper-case!
str() return a string




print相关:
Python2.7x和Python3.x区别
print think of print ->Python2.7x
print (think of print) ->Python3.x


print "The value of pi is around " + 3.14  this is error!
print "The value of pi is around " + str(3.14) this is right!


print("%.2f" % total)
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)




Unfortunately, strings in Python are immutable—you can't change them once they're created.


跨行代码用\
print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)




时间库(datetime library)
打印出: mm/dd/yyyy hh:mm:ss
from datetime import datetime
now = datetime.now()
print now
print now.month 
print now.day 
print now.year 
print now.hour
print now.minute
print now.second
print str(now.month) +"/"+str(now.day) +"/"+ str(now.year)
print str(now.hour)+":"+str(now.minute)+":"+str(now.second)
print str(now.month) +"/"+str(now.day) +"/"+ str(now.year)+" "+str(now.hour)+":"+str(now.minute)+":"+str(now.second)




if 。。:
elif 。。:
else :


answer = raw_input("Type left or right and hit 'Enter'.").lower()无论输入的是大小写,都转化为小写。


boolean just is True or False


优先级:not and  or


python的str类型中,有如下方法。 
str.isalpha 
str.isdigit 
判断该字符串是否全是字母或者数字。


项目一:English to Pig Latin
pyg = 'ay'


original = raw_input('Enter a word:')
word = original.lower()#输入全部转化为小写
first=word[0]#取首字母
if len(original) > 0 and original.isalpha():#判断输入是否为空 and 是否全是字母
    print original
    if first=='a' or first=='e' or first=='i' or first=='o' or first=='u':#统计是否为元音
        new_word=word+pyg
        print new_word
    else:
        new_word=word[1:]+first+pyg
        print new_word
else:
    print "empty" 
    
    
def favorite_actors(*name):
    """Prints out your favorite actorS (plural!)"""
    print "Your favorite actors are:" , name
    
    
favorite_actors("Michael Palin", "John Cleese", "Graham Chapman")
多参数用*传递    
3.F(*arg1)
上 面俩个方式是有多少个形参,就传进去多少个实参,但有时候会不确定有多少个参数,则此时第三种方式就比较有用,它以一个*加上形参名的方式来表示这个函数 的实参个数不定,可能为0个也可能为n个。注意一点是,不管有多少个,在函数内部都被存放在以形参名为标识符的tuple中。
>>> def a(*x):
if len(x)==0:
print 'None'
else:
print x
>>> a(1)
(1,)        #存放在元组中
>>> a()
None
>>> a(1,2,3)
(1, 2, 3)
>>> a(m=1,y=2,z=3)


Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevel-
a(m=1,y=2,z=3)
TypeError: a() got an unexpected keyword argument 'm'




4.F(**arg1)
形参名前加俩个*表示,参数在函数内部将被存放在以形式名为标识符的dictionary中,这时调用函数的方法则需要采用arg1=value1,arg2=value2这样的形式。
>>> def a(**x):
if len(x)==0:
print 'None'
else:
print x  
>>> a()
None
>>> a(x=1,y=2)
{'y': 2, 'x': 1}      #存放在字典中
>>> a(1,2)            #这种调用则报错


Traceback (most recent call last):
File "<pyshell#25>", line 1, in -toplevel-
a(1,2)
TypeError: a() takes exactly 0 arguments (2 given)


dir(math)查看math相关属性


type(参数)查看参数类型


向列表中添加元素.append(元素)每次只能接受一个元素。


my_list.index("dog")返回dog在列表中的索引号
my_list.insert(4,"cat")列表中索引号为4的地方出入cat
my_list.sort()排序之后不产生新的列表,改变的是原来的列表
del dict_name[key_name] 删除字典的元素
dict_name[key] = new_value字典中添加新值


求列表元素的和直接用sum(列表名)




n.pop(index) will remove the item at index from the list and return it to you:
n = [1, 3, 5]
n.pop(1)
# Returns 3 (the item at index 1)
print n
# prints [1, 5]


n.remove(item) will remove the actual item if it finds it:
n.remove(1)
# Removes 1 from the list,
# NOT the item at index 1
print n
# prints [3, 5]


del(n[1]) is like .pop in that it will remove the item at the given index, but it won't return it:
del(n[1])
# Doesn't return anything
print n
# prints [1, 5]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值