首页 > 编程语言 > 详细

python基础语法

时间:2020-05-05 09:50:40      阅读:56      评论:0      收藏:0      [点我收藏+]

1、

{i:5 for i in [1,2,3] } 

执行结果{1: 5, 2: 5, 3: 5}

2、常用指令

1)?显示变量的通用信息

 ?? 如果可以的话显示源码

a = [1,2,3] 
a?
np.*load*?

执行结果:

np.__loader__
np.load
np.loads
np.loadtxt

2)%命令

%run aa.py  #执行py文件
%load aa.py  #导入py文件
%paste   #执行剪切板的代码
%cpaste  #执行
%timeit a= [n for n in range(1000)]  #计时
%matplotlib inline    #显示图片

3) 获取类型

type(5)
isinstance(5.0,(int,float))
getattr(data,lower) #通过属性获取方法名称

def isiterable(obj): #是否枚举类型
    try:
        iter(obj)
        return True
    except TypeError: # not iterable
        return False
isiterable(a string)
1 is not 2  #检查是否是同样对象)

int(3) #类型转化
type(None)

datetime.strptime(‘20091031 14:59:36‘, ‘%Y%m%d %H:%M:%S‘) #字符串转化为日期

4)表达式

value = true-expr if condition else false-expr

x=5
Non-negative if x >= 0 else Negative

5)元组列表

values=1,2,3,4,5
a,b,*_ = values   #元组拆包
list((1,2,3))  #元组转列表

alist =[2,3,7,2]
2 in alist   #判断是否在列表里

alist + [a,b,c,4]  #合并列表
#切片
seq=[7,2,3,7,5,6,0,1]
seq[-4:]      #[5, 6, 0, 1] 从结尾倒数第四个开始取数
seq[-6:-2]   #[6, 3, 5, 6]
seq[::2]       #[7, 3, 3, 6, 1] 间隔2个取一次数
seq[::-1]     #[1,0,6,5,3,6,3,2,7]  反转

some_list = [foo, bar, baz]
mapping = {}
for i, v in enumerate(some_list):
    mapping[i]=v
#{0: ‘foo‘, 1: ‘bar‘, 2: ‘baz‘} 获取值

#zip 生成元组
seq1 = [foo, bar, baz]
seq2 = [one, two, three]
zipped = zip(seq1, seq2)
list(zipped)
#[(‘foo‘, ‘one‘), (‘bar‘, ‘two‘), (‘baz‘, ‘three‘)]

for i, (a, b) in enumerate(zip(seq1, seq2)):
    mapping[i] =(a, b)
mapping
#{0: (‘foo‘, ‘one‘), 1: (‘bar‘, ‘two‘), 2: (‘baz‘, ‘three‘)}

tupt =[(foo, one), (bar, two), (baz, three)]
a,b =zip( *tupt )
a,b
#((‘foo‘, ‘bar‘, ‘baz‘), (‘one‘, ‘two‘, ‘three‘))


list(reversed(range(10)))  #反转
#[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

6)字典

#序列转字典1
#mapping = {}
#for key, value in zip(key_list, value_list):
#mapping[key] = value

#序列转字典2
mapping = dict(zip(range(5), reversed(range(5))))
mapping
#{0: 4, 1: 3, 2: 2, 3: 1, 4: 0}

#获取设置字典默认值

value = some_dict.get(key, default_value)

words = [apple, bat, bar, atom, book]
#方法一
by_letter = {}
for word in words:
    letter=word[0]
    if letter  in by_letter:
        by_letter[letter].append(word)
    else:
        by_letter[letter]= [word]
#方法二

for word in words:
    letter = word[0] 
    by_letter.setdefault(letter, []).append(word)
#检查是否可以hash
hash(string)
#如果希望数组作为key的话需要转我元组
d={}
d[tuple([1, 2, 3])] = 5

 7)集合

#创建集合set的2种方式
set([2, 2, 2, 1, 3, 3])
{2,2,2,1,3,3}
#输出{1,2,3}

8)list、set、dic

#[expr for val in collection if condition]
strings = [a, as, bat, car, dove, python]
[x.upper() for x in strings if len(x) > 2]
#[‘BAT‘, ‘CAR‘, ‘DOVE‘, ‘PYTHON‘]
#字典
#dict_comp = {key-expr : value-expr for value in collection if condition}
#集合
#set_comp = {expr for value in collection if condition}
{len(x) for x in strings}
set(map(len, strings))
# 输出:{1, 2, 3, 4, 6}
 {val : index for index, val in enumerate(strings)}
#{‘a‘: 0, ‘as‘: 1, ‘bat‘: 2, ‘car‘: 3, ‘dove‘: 4, ‘python‘: 5}

 all_data = [[John, Emily, Michael, Mary, Steven],[Maria, Juan, Javier, Natalia, Pilar]]
  names_of_interest = [] 
for names in all_data:
    enough_es = [name for name in names if name.count(e) >= 2] 
    names_of_interest.extend(enough_es)
[name for names in all_data for name in names if name.count(e) >= 2]
#[‘Steven‘]

 9) 函数

#yield使用
def squares(n=10):
    print(Generating squares from 1 to {0}.format(n ** 2))
    for i in range(1, n + 1):
        yield i**2
gen = squares()
for x in gen:
    print(x,end= )
#Generating squares from 1 to 100
#1 4 9 16 25 36 49 64 81 100 

 

 

python基础语法

原文:https://www.cnblogs.com/excellence/p/12811723.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!