c1 = "hello" c2 = "world" sentence = c1.strip('""') + ' ' + c2.strip('""') + '!' print('The first word is %s, and the second word is %s' % (c1, c2)) print(sentence)
The first word is hello, and the second word is world
hello world!
import math print(math.log(math.e))
1.0
import time now = time.strptime('2021-11-23', '%Y-%m-%d') print(now)
time.struct_time(tm_year=2021, tm_mon=11, tm_mday=23, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=1, tm_yday=327, tm_isdst=-1)
time.strftime('%Y-%m-%d', now)
‘2021-11-23’
import datetime BirthDay = datetime.date(1998,9,12) NowDay = datetime.date(2021,11,23) deltaDay = NowDay - BirthDay deltaDay.days
8473
my_list = [0, 1, 2, 3, 4, 5]
#包头不包尾 print('[4]', my_list[4]) print('[0:4]', my_list[0:4]) print('[4,5]', my_list[4:5]) print('[:4]', my_list[:4]) print('[-4]', my_list[-4]) print('[0:4:2]', my_list[0:4:2]) print('[-5:-1:]', my_list[-5:-1:]) print('[-2::-1]', my_list[-2::-1])
[4] 4
[0:4] [0, 1, 2, 3][4,5] [4]
[:4] [0, 1, 2, 3]
[-4] 2
[0:4:2] [0, 2]
[-5:-1 :] [1, 2, 3, 4]
[-2::-1] [4, 3, 2, 1, 0]
#修改值
修改的位置不能超过索引my_list[3] = 'RuanYaohuang' my_list[4] = 'Max' print(my_list)
添加元素[0, 1, 2, ‘RuanYaohuang’, ‘Max’, 5]
my_list.append('Add element') my_list.extend(['long', 'wan']) print(my_list)
[0, 1, 2, 3, 4, 5, ‘Add element’, ‘long’, ‘wan’]
c1 = [12, 13, 14, 15] c2 = ['R', 'y', 'h'] c2.insert(1,c1) print(c2)
[‘R’, [12, 13, 14, 15], ‘y’, ‘h’]
print(c2.pop(1)) print(c2)
判断元素是否在列表中[12, 13, 14, 15]
[‘R’, ‘y’, ‘h’]
print('R' in c2) print('14' in c2)
判断字符在列表中出现的次数True
False
print(c2.count('R'))判断字符在列表中的索引
print(c2.index('h'))
1 2range生成整数列表
print(range(10)) print(range(-5, 5)) print(range(-10, 10, 2)) print(range(16, 10, -1))
元组也是相当于列表,但是元组的数据不能修改range(0, 10)
range(-5, 5)
range(-10, 10, 2)
range(16, 10, -1)
score = [90, 98, 88] studentID = ("Ruanyaohuang", "Wangruoxi", "Wuhongcheng", score) print(studentID)
(‘Ruanyaohuang’, ‘Wangruoxi’, ‘Wuhongcheng’, [90, 98, 88])
try: studentID[1] = 'fu' except TypeError: print('TypeError')
TypeError
print('Ruanyaohuang' in studentID) # 0,1索引的值 print(studentID[0:2]) # 出现次数 print(studentID.count('Wangruoxi')) # 出现位置的索引 print(studentID.index('Wangruoxi')) # 元组的长度 print(len(studentID))
set():进行集合 *** 作,消除重复元素 set中可以使列表,字典,字符串True
(‘Ruanyaohuang’, ‘Wangruoxi’)
1
1
4
c3 = set(c2) print(c3) c3.add('W') print(c3) c3.remove('R') print(c3)
{‘R’, ‘h’, ‘y’}
{‘W’, ‘R’, ‘h’, ‘y’}
{‘W’, ‘h’, ‘y’}
a = set("abcdefghj") b = set("klmcedf") print(a) print(b) # 交集 x = a&b print('交集:', x) # 并集 x = a|b print('并集:', x) # 差集 x = a-b print('差集:', x) # 去除重复元素
{‘f’, ‘e’, ‘b’, ‘c’, ‘j’, ‘h’, ‘g’, ‘a’, ‘d’}
{‘m’, ‘l’, ‘f’, ‘e’,‘c’, ‘k’, ‘d’}
交集: {‘e’, ‘d’, ‘f’, ‘c’}
并集: {‘m’, ‘l’, ‘f’, ‘e’, ‘b’,‘c’, ‘j’, ‘h’, ‘g’, ‘k’, ‘a’, ‘d’}
差集: {‘b’, ‘j’, ‘h’, ‘g’, ‘a’}
#Python中的字典dict也叫做关联数组,用大括号{}括起来, #在其他语言中也称为map,使用键-值(key-value)存储, #具有极快的查找速度,其中key不能重复。 k = {"name": "Ruanyaohuang", "home": "HeBei"} print(k["home"]) print(k.keys()) print(k.values())
k[“like”] = “Music”
k[“name”] = “Ryh”
print(k)
HeBei
dict_keys(['name', 'home']) dict_values(['Ruanyaohuang', 'HeBei'])
{‘name’: ‘Ryh’, ‘home’: ‘HeBei’, ‘like’: ‘Music’}
#通过dict提供的get方法,如果key不存在,可以返回-1 k.get("edu", -1)
-1
#删除键值对 k.pop('like')
print(k)
--------------------------------------------------------------------------- KeyError Traceback (most recent call
last) in ()
1 # 删除键值对
----> 2 k.pop(‘like’)
3 print(k)KeyError: ‘like’
type(c2) # 将列表转换成元组 tuple(c2) # 将字典转换为列表,但是只有key
zip函数可以将列表,元组,集合,字典“缝合”起来list(k)
[‘name’, ‘home’]
z1 = zip(('A', 'B', 'C'), [1, 2, 3, 4]) print(z1) print(dict(z1))
{‘A’: 1, ‘B’: 2, ‘C’: 3}
a = 1 while a<10: if a<5: print(a) else: print('Hello') a+=1 else: print("Done")
1
2
3
4
Hello
Hello
Hello
Hello
Hello
Done
heights = {'Yao':226, 'Sharq':216, 'AI':183} for i in heights: print(i, heights[i])
Yao 226
Sharq 216
AI 183
for key, value in heights.items(): print(key, value)
Yao 226
Sharq 216
AI 183
total = 0 for i in range(1, 101): total += i print(total)
5050
# break continue pass # break:跳出循环 # continue:跳出当前循环,继续下一次循环 # pass:占位符,什么也不做 for i in range(1, 5): if i==3: break print(i)
1
2
# continue:跳出当前循环,继续下一次循环 for i in range(1, 5): if i==3: continue print(i)
1
2
4
# pass:占位符,什么也不做 for i in range(1, 5): if i==3: pass print(i)
1
2
3
4
fruits = ["apple", "banana", "watermelon"] # [<表达式> for (条件变量) in (集合)] [x.strip('"') for x in fruits] ['apple', 'banana', 'watermelon'] test_list = [] for x in fruits: x = x.strip('"') test_list.append(x) print(test_list)
[‘apple’, ‘banana’, ‘watermelon’]
# [<表达式> for (条件变量) in (集合) if <'True or False'表达式>] [x**2 for x in range(21) if x%2] [1, 9, 25, 49, 81, 121, 169, 225, 289, 361] test_list = [] for x in range(21): if x%2: x=x**2 test_list.append(x) test_list
[1, 9, 25, 49, 81, 121, 169, 225, 289, 361]
# [<表达式> if <'True or False'表达式> else <表达式> for (条件变量) in (集合) ] [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] d = {'x':'A', 'y':'B', 'z':'C'} [k + '=' + v for k, v in d.items()] ['x=A', 'y=B', 'z=C'] test_list = [] for k, v in d.items(): x = k + '=' + v test_list.append(x) test_list
[‘x=A’, ‘y=B’, ‘z=C’]
# 定义函数 def my_abs(x): if x>=0: return x else: return -x my_abs(-9)
9
fruit = ['apple', 'banana', 'melon'] def filter_fruit(somelist, d): for i in somelist: if i==d: somelist.remove(i) else: pass print(filter_fruit(fruit, 'melon')) print(fruit)
None
[‘apple’, ‘banana’]
def test(i, j): k = i * j return i, j, k a, b, c = test(4, 5) print(a, b, c) type(test(4 , 5))
4 5 20
tuple
# 把另一个函数作为参数传入一个函数,这样的函数称为高阶函数 # 函数本身也可以赋值给变量,函数与其它对象具有同等地位 reflect = abs reflect(-9) 9 def add(a,b,f): return f(a) + f(b) # 都取正数后相加 add(7, -5, reflect)
12
my_list = [-1, 2, -3, 4, -5, 6, -7] map(abs, my_list)
from functools import reduce def powerAdd(a, b): return pow(a, 2) + pow(b, 2) reduce(powerAdd, my_list)
3560020598205630145296938
def is_odd(x): return x%3 filter(is_odd, my_list)
sorted(my_list)
[-7, -5, -3, -1, 2, 4, 6]
my_char = ['Apple', 'orange', 'Peach', 'banana'] my_char[0].lower() my_char[1].lower() sorted(my_char)
[‘Apple’, ‘Peach’, ‘banana’, ‘orange’]
# 返回函数: 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回 def powAdd(x, y): def power(n): return pow(x,n) + pow(y,n) return power myF = powAdd(3, 4) myF(2)
25
# 匿名函数:高阶函数传入函数时,不需要显式地定义函数,直接传入匿名函数更方便 f = lambda x: x*x print('f(x)=', f(4)) # 等同于 def g(x): return x*x print('g(x)=', g(4))
f(x)= 16
g(x)= 16
my_list = [-1, 2, -3, 4, -5, 6, -7] reduce(lambda x, y: x+y, map(lambda x: x*x, my_list))
140
def powAdd1(x, y): return lambda n: pow(x,n) + pow(y,n) lamb = powAdd1(3,4) lamb(2)
25
import keyword print(keyword.kwlist)
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’,
‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’,
‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’,
‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’,
‘while’, ‘with’, ‘yield’]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)