Python学习记录-基础2

1 字符串

String = "I am angry."  #  ' 或 " 都可以

可以使用引号('或")来创建字符串,不支持单字符

>>> a = "You are"
>>> b = " naive"
>>> c = a + b
>>> d = "%s!!!"%c  # or d = "%s!!!" %(a+b)
>>> d
'You are naive!!!'
>>> a[2]    
'u'
>>> b[1:]
'aive'
>>> b[2:5]
'ive'
>>> b[:3]
'nai'
>>> a[0:3]
'you'
>>> a[0:4]
'you '
>>> a[5:-1]
'r'
>>> a[3:-1]
' ar'
>>> a[::2]  #步长为2
'yuae'
>>> b[::-1]
'evian'

字符串操作方法:查看

2 列表

列表的数据项不需要具有相同的类型

>>> list1=['1',1,'2.5',250] 
>>> list1
['1', 1, '2.5', 250]
>>> list2=['huang','wen','han']
>>> list1.append('h') #添加到末尾
>>> list1
['1', 1, '2.5', 250, 'h']
>>> list1.insert(4,'y')  #添加到任意位置
>>> list1
['1', 1, '2.5', 250, 'y', 'h']
>>> list1[4]='H'  #修改元素
>>> list1
['1', 1, '2.5', 250, 'H', 'h']
>>> list1.extend(list2)  #扩展列表 also list1.extend([1,2,3])
>>> list1
['1', 1, '2.5', 250, 'H', 'h', 'huang', 'wen', 'han']
>>> del list1[6:]  #删除元素
>>> list1
['1', 1, '2.5', 250, 'H', 'h']
>>> list3 = [list1,list2]  #列表嵌套!可用于构建矩阵
>>> list3
[['1', 1, '2.5', 250, 'H', 'h'], ['huang', 'wen', 'han']]
>>> list3.pop(0)  #移除元素
['1', 1, '2.5', 250, 'H', 'h']
>>> list3
[['huang', 'wen', 'han']]
#查询用 in 或 not in 。。?

注意append和extend的区别:

>>> list1=[1,2,3]
>>> list2=[3,4,5]
>>> list1.append(list2)
>>> list1
[1, 2, 3, [3, 4, 5]]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, [3, 4, 5], 3, 4, 5]
#不能直接赋值:list3 = list1.append(list2)

将列表当作堆栈、列表推导式:

#堆栈,后进先出
In [1]: stack = [1,2,3]
In [2]: stack.append(4)
In [3]: stack.append(5)
In [4]: stack
Out[4]: [1, 2, 3, 4, 5]
In [5]: stack.pop()
Out[5]: 5
In [6]: stack
Out[6]: [1, 2, 3, 4]
#列表推导式
In [7]: [2*x for x in stack]
Out[7]: [2, 4, 6, 8]
In [8]: [x*3 for x in stack if x>5]
Out[8]: []
In [9]: stack
Out[9]: [1, 2, 3, 4]
In [10]: [x*3 for x in stack if x>2]
Out[10]: [9, 12]

其他操作方法:查看

3 字典

字典是可变容器模型,可存储任意类型对象。键须是唯一的,值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

In [1]: data = { 'name':'van','age':23}  #创建
In [2]: data
Out[2]: {'name': 'van', 'age': 23}
In [3]: data['age']  #查看
Out[3]: 23
In [4]: data['career'] = 'artist'  #添加/修改
In [5]: data
Out[5]: {'name': 'van', 'age': 23, 'career': 'artist'}
In [6]: del data['career']  #删除
In [7]: data
Out[7]: {'name': 'van', 'age': 23}
In [8]: data.get('age')  #可以防止获取空键时报错
Out[8]: 23
In [9]: if 'age' in data.keys():  #遍历所有key
   ...:     print('I find age.')
   ...:    
I find age.
In [10]: data.values()
Out[10]: dict_values(['van', 23])

其他操作方法:查看

4 示例:名片管理系统(未完待续)

#Interface Interaction
print('-'*40)
print('Personnel Data Management System V1.0')
print("1.Add a Person")
print("2.Del a Person")
print("3.Change a Person")
print("4.Find a Person")
print("5.Display all person")
print("6.Exit")
print('-'*40)
#A list for personnel's data
person_list = []
while True:
	#Get Input
	num = int(input('Please input the number:\n'))
	#Execute some funtion
	if num ==1:
		add_name = input("Please input a new name: ")
		add_qq = input("Please input %s's qq: "%add_name)
		add_weixin = input("Please input %s's weixin: "%add_name)
		add_addr = input("Please input %s's address: "%add_name)
		#A new dict for new person
		new_dict = {}
		new_dict['name'] = add_name
		new_dict['qq'] = add_qq
		new_dict['weixin'] = add_weixin
		new_dict['addr'] = add_addr
		#put a dict in a list
		person_list.append(new_dict)
		print(person_list)
	elif num ==3:
		pass
	elif num ==4:
		find_flag = 0 #control flag
		find_name = input("Please input the name you want to find: \n")
		for temp in person_list:
			if find_name == temp['name']:
				print("I've find it.")
				print("%s\t%s\t%s\t%s\t"%(temp['name'],temp['qq'],temp['weixin'],temp['addr']))
				find_flag = 1
				break
		if find_flag ==0 :
			print("I can't find it")
	elif num ==5:
		print("Name\tQQ\tWeixin\tAddress\t")
		for temp in person_list:
			print("%s\t%s\t%s\t%s\t"%(temp['name'],temp['qq'],temp['weixin'],temp['addr']))
	elif num ==6:
		print("Thank you for using......")
		print(' '*40)
		break
	else:
		print('Input wrong! Please retry.')
		print(' '*40)

5 元组

元组的元素不能修改。使用圆括号。逗号分隔。

In [1]: tup = ('1',1,'2',3)
In [2]: tup
Out[2]: ('1', 1, '2', 3)
In [3]: tup2=(4)
In [4]: type(tup2)
Out[4]: int
In [5]: tup3=(4,)
In [6]: type(tup3)
Out[6]: tuple
#除了不能修改(只能查询),其他操作类似于列表
#拆包
data = { 'name':'han', 'age':23}
for temp in data.items():
    print("key=%s,value=%s" %(temp[0],temp[1]) )  
#这样
for A,B in data.items():
    print("key=%s,value=%s" %(A,B) )
#同样输出:
key=name,value=han
key=age,value=23

6 集合

集合是无序不重复元素的序列。使用大括号 { } 或者 set() 函数创建集合。创建空集合必须用 set() ,因为 { } 创建空字典。

>>> app = { 'qq', 'weixin', 'weibo' }
>>> app 
{'weixin', 'qq', 'weibo'}
>>> 'qq' in app
True
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'b', 'c', 'r', 'd', 'a'}
>>> b
{'c', 'l', 'z', 'm', 'a'}
>>> a-b
{'b', 'd', 'r'}
>>> a|b
{'b', 'c', 'r', 'l', 'd', 'z', 'm', 'a'}
>>> a&b
{'c', 'a'}
>>> a^b
{'b', 'l', 'd', 'r', 'z', 'm'}

7 迭代器、生成器

迭代是访问集合元素的一种方式。迭代器可以记住遍历的位置。
迭代器对象从集合的第一个元素开始直到所有的元素被访问完结束,只能往前不能后退。
迭代器有两个基本的方法:iter() 和 next()。

In [1]: list = [1,2,3,4]
In [2]: it = iter(list)  #创建迭代器对象
In [3]: next(it)  #访问迭代器对象
Out[3]: 1
In [4]: next(it)
Out[4]: 2
In [5]: next(it)
Out[5]: 3
In [6]: it = iter(list)
In [7]: for x in it:  #遍历
   ...:     print(x,end="")
   ...:     
1234

使用了 yield 的函数被称为生成器(generator)。调用一个生成器函数,返回的是一个迭代器对象。
在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。

import sys
def fibonacci(n): # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
    try:
        print (next(f), end=" ")
    except StopIteration:
        sys.exit()

猜你喜欢

转载自blog.csdn.net/muerjie5669/article/details/81325679