python学习_14

2023-01-31 01:01:18 python 学习

exec(str)
可以执行多行语句,语句块,没有返回值

command = """
... a= [1,2,3]
... for i in a:
... print(i)
... """
exec(command)
1
2
3

a = [1,2,3]
for i in a:
... exec("print(" + str(i) + ")")
...
1
2
3

eval(str)
只能执行单行语句,有返回值

a = eval("2*4")
a
8

s = "print(" + str(10) + ")"
eval(s)
10

函数引用
函数名可以赋值给其他的变量引用,用引用加括号可以直接调用原函数

a = abs
a(-10)
10

def func(f):
... print(f(-1))
...
func(abs)
1

函数解包传递参数
解包元组传参

def func(args):
... print(args)
...
t = (2,3,4)
func(
t) #可以利用星号加上元组名传递参数
(2, 3, 4)

 def add(a,b):return a+b
...
 add(*(1,2))
3

解包字典传参

def func(kwargs):
... for k,v in kwargs.items():
... print(k,v)
...
d = {"name":"huhongqiang","age":18,"sex":"m"}
func(
d)
name huhongqiang
age 18
sex m

def sub(a,b):
... return a - b
...
sub(**{"a":3,"b":2})
1

习题8:[1,2,3,4,5] 变成 [2,3,4,5,1]
方法1:

a=[1,2,3,4,5]

result = []
result.append(a[-1])
result.extend(a[0:4])
print(result)

方法2:

result = []
result.append(a[-1])
for v in a[0:4]:
    result.append(v)
print(result)

方法3:

a=[1,2,3,4,5]

result = []

for v in a[0:4]:
    result.append(v)

result.insert(0,a[-1])
print(result)

习题9:统计字符串的个数

l = [1,2,"s",[1,23],{1:2},(1,2),set([1,2]),"b"]

str_number = 0
for v in l:
    if isinstance(v,str):
        str_number += 1
print(str_number)

习题10:统计列表中所有类型数据的个数

l = [1,2,"s",[1,23],{1:2},(1,2),set([1,2]),"b"]

d = {"str":0,"list":0,"tuple":0,"int":0,"set":0}
for v in l:
    if isinstance(v,str):
        d["str"] += 1
    elif isinstance(v,list):
        d["list"] += 1
    elif isinstance(v,tuple):
        d["tuple"] += 1
    elif isinstance(v,set):
        d["set"] += 1
    #elif isinstance(v,int):
        #d["int"] += 1
print(d)

习题11:求列表中所有数字的和,包括数字字符串

a = [1,2,3,[4,5,6],{1:6,2:8,"a":"12",3:4}]

result = 0
for value in a:
    if isinstance(value,int):
        result += value
    elif isinstance(value,list):
        for v in value:
            if isinstance(v,int):
                result += v
    elif isinstance(value,dict):
        for key in value.keys():
            if isinstance(key,int):
                result += key
        for v in value.values():
            if isinstance(v,int):
                result += v

            elif v.isdigit():
                result += int(v)
print(result)

a = [1,2,3,[4,5,6],{1:6,2:8,"a":"12",3:4}]
这个地方有个小坑,判断字典value值是否是数字的时候,要先把判断int的放在前面,否则会报错;

result = 0
for value in a:
    if isinstance(value,int):
        result += value
    elif isinstance(value,list):
        for v in value:
            if isinstance(v,int):
                result += v
    elif isinstance(value,dict):
        for key in value.keys():
            if isinstance(key,int):
                result += key
        for v in value.values():
            #这个先判断了是否是数字字符串,因为整数没有isdigit()方法
            if v.isdigit():
                result += v

            elif isinstance(v,int):
                result += int(v)
print(result)  

相关文章