Python学习(九)三元运算、函数

1、三元运算(三目运算)

 #v = 前面 if 条件 else 后面
# if '条件':
#     v ='前面'
# else :
#     v ='后面'

# 让用户输入值,如果值是整数,则装换成整数,否则赋值为None
data = input('>>>')
value = int(data) if data.isdecimal() else None  # 省略写法
print(value)

2、函数

'''函数的基本结构
def 函数名():
    #函数内容
    pass
#函数的执行
函数名()'''

# 1、函数计算列表 info =[11,22,33]中所有元素的和
def list_sum(a):
    count = 0
    for i in a:
        count += i
    return count

v = list_sum([11, 22, 33])
print(v)

# 2、写函数,将两个列表拼接起来
def list_join(q1, q2):
    result = []
    result.extend(q1)
    result.extend(q2)
    print(result)

q = list_join([1, 2], [3, 4])
print(q)

# 3、写函数,计算一个列表中有多少个数字,打印:列表中有%d个数字
# 提示:type('x') == int 判断是否是数字
def list_number(b):
    count = 0
    for i in b:
        if type(i) == int:
            count += 1
    return count

list_1 = list_number(['a', 's', 'd', 1, 2, 3, ])
print('列表中有%d个数字' % (list_1,))

# 4、写函数,计算一个列表中偶数索引位置的数据构造成另一个列表,并返回
def list_even_number(arg):
    even = arg[2::2]
    return even

x = list_even_number([1, 2, 3, 4, 5, 6, 7, 8, 9, ])
print(x)

# 5、读取文件,将文件的内容构造成指定格式,并返回
'''a.log文件
    alex|11|22
    aaaa|ssss|99
目标结构:
A.['alex|11|22','aaaa|ssss|99']
B.[['alex|11|22'],['aaaa|ssss|99']]
C.[{'name':'alex','pwd':'11','age':'22'},{'name':'aaaa','pwd':'ssss','age':'99'}]
'''


def list_a(arg):
    with open('a-log.txt', mode='r', encoding='utf-8') as fhl:
        data1 = fhl.read()
        data1 = data1.split()
        return data1


a = list_a('a')
print(a)


def list_b(arg):
    count = []
    with open('a-log.txt', mode='r', encoding='utf-8') as fhl:
        data2 = fhl.readline()
        data2 = data2.split()
        count.append(data2)

        data2_1 = fhl.readline()
        data2_1 = data2_1.split()
        count.append(data2_1)
        return count


b = list_b('b')
print(b)


def list_c(arg):
    count = {}
    count1 = {}
    content = []
    with open('a-log.txt', mode='r', encoding='utf-8') as fhl:
        data3 = fhl.readline()
        data3 = data3.replace('\n', '|')
        data3 = str(data3)
        data3 = data3.split('|')

        data3_1 = fhl.readline()
        data3_1 = data3_1.split('|')

        val = ['name', 'pwd', 'age']
        for x in range(len(val)):
            count[val[x]] = data3[x]
        content.append(count)
        for x in range(len(val)):
            count1[val[x]] = data3_1[x]
        content.append(count1)
        return content


c = list_c('c')
print(c)

 

上一篇:04_Numpy模块的使用


下一篇:NumPy笔记:多维度数组