python面试题100+

面试题转自:https://mp.weixin.qq.com/s/EmJMIWB64ZzN2NddkmKG4g
答案仅供参考,写的不够简便或者写错了,还请大神给予指出

1.1、交换
已知 a的值为'hello',b的值为'world',如何交换a和b的值?
得到a的值为'world',b的值为'hello'
def change_value(a='hello', b='world'):
    x = a
    a = b
    b = x
    return a, b
1.2、回文
回文的定义:'回文' 就是正读倒读都一样的。
如奇数个:'98789',这个数字正读是'98789' 倒读也是'98789'。
偶数个数字'3223'也是回文数。
字母 'abcba' 也是回文。
判断一个字符串是否是回文字符串,是打印True, 不是打印False
a==a[::-1]

content = 'abcsba'
if list(content) == [i for i in reversed(content)]:
print('Ture')
else:
print('False')
def out(content='abcsba'):
    state = False
    content = list(content)
    if len(content) < 2:
        return False
    for i in range(len(content)):
        if content[i] == content[len(content) - i - 1]:
            state = True
            continue
        else:
            return False
    return state
1.3、字符串切割
已知一个字符串为 'hello_world_yoyo', 如何得到一个队列 ['hello','world','yoyo']
def out(content='hello_world_yoyo'):
    return content.split('_')
1.4、拼接字符串
有个列表 ['hello', 'world', 'yoyo']如何把把列表里面的字符串联起来,
得到字符串 'hello_world_yoyo'
def out(content=None):
    if content is None:
        content = ['hello', 'world', 'yoyo']
    return '_'.join(content)
1.5、替换字符
把字符串 s 中的每个空格替换成'%20'
输入:s = 'We are happy.'
输出:'We%20are%20happy.'
def out(content=None):
    if content is None:
        content = 'We are happy.'
    return content.replace(' ', '%20')
1.6、九九乘法表
打印99乘法表
def out(content=9):
    for i in range(1, content + 1):
        for j in range(1, i + 1):
            print('{} * {} = {}	'.format(i, j, i * j), end='')
        print()
1.7、字符下标
找出单词 'welcome' 在 字符串'Hello, welcome to my world.' 中出现的位置,找不到返回-1
从下标0开始索引
def out(content='Hello, welcome to my world.', words='welcome'):
    if content.find(words):
        return content.find(words)
    else:
        return -1
1.8、统计字符串出现次数
统计字符串'Hello, welcome to my world.' 中字母w出现的次数
统计单词 my 出现的次数
def out(content='Hello, welcome to my world.', words='my', char='w'):
    return content.count(words), content.count(char)
1.9 统计每个字符出现的次数
题目:输入一个字符串str, 输出第m个只出现过n次的字符,如在字符串 gbgkkdehh 中,
找出第2个只出现1 次的字符,输出结果:d
def out(content='gbgkkdehh', m=2, n=1):
    content = list(content)
    d = {}
    lst = []
    for i in content:
        d[i] = d.get(i, 0) + 1

    for k, v in d.items():
        if n == v:
            lst.append(k)
    return lst[m - 1]
1.10 判断字符a含b
判断字符串a='welcome to my world' 是否包含单词b='world'
包含返回True,不包含返回 False
def out(content='welcome to my world', word='world'):
    if content.__contains__(word):
        return True
    else:
        return False
1.11 查找字符首次出现位置
输出指定字符串A在字符串B中第一次出现的位置,如果B中不包含A,则输出-1
从 0 开始计数
A = 'hello'
B = 'hi how are you hello world, hello yoyo !'
def out(content='hi how are you hello world, hello yoyo !', word='hello'):
    if content.__contains__(word):
        return content.find(word)
    else:
        return -1
1.12 查找字符串最后一次出现位置
输出指定字符串A在字符串B中最后出现的位置,如果B中不包含A,则输出-1
从 0 开始计数
A = 'hello'
B = 'hi how are you hello world, hello yoyo !'
def out(content='hi how are you hello world, hello yoyo !', word='hello'):
    if content.__contains__(word):
        return content.rfind(word)
    else:
        return -1
1.13判断奇数偶数
给定一个数a,判断一个数字是否为奇数或偶数
a1 = 13
a2 = 10
def out(a=13):
    if a % 2 == 0:
        return '偶数'
    else:
        return '奇数'
1.14判断一个姓名是否姓王
输入一个姓名,判断是否姓王
a = '王五'
b = '老王
def out(content='王五', word=''):
    if content[0] == word:
        return True
    else:
        return False
1.15判断是不是数字
如何判断一个字符串是不是纯数字组成
a = '123456'
b = 'yoyo123'
def out(content='123456'):
    if str(content).isdigit():
        return True
    else:
        return False
1.16字符串大小写转换
将字符串 a = 'This is string example….wow!' 全部转成大写
字符串 b = 'Welcome To My World' 全部转成小写
print(a.upper())
print(b.lower())
1.17字符串去掉首尾空格
将字符串 a = ' welcome to my world '首尾空格去掉
print('  welcome to my world   '.strip(' '))
1.18字符串去掉左边指定空格或字符
将字符串a = ' welcome to my world !'左边的空格去掉
print('  welcome to my world !'.lstrip(' '))
1.19字符串去掉右边指定空格或字符
将字符串a = ' welcome to my world ! '右边的空格去掉
print(a.rstrip(' '))
1.20 去除字符串里面所有的空格
将字符串a = ' welcome to my world ! '里面的所有空格都去掉
print(a.replace(' ', ''))
1.21字符串去重后排序
s = 'ajldjlajfdljfddd',去重并从小到大排序输出'adfjl'
def out(content='ajldjlajfdljfddd'):
    content = set(content)
    return sorted(content)
1.22字符串去重保留顺序
s = 'ajldjlajfdljfddd',去重保留原来的顺序,输出'adfjl'
def out(content='ajldjlajfdljfddd'):
    result = ''
    for i in content:
        if i in result:
            continue
        else:
            result += i
    return result
1.23画菱形
题目 打印出如下图案(菱形):
*
***
*****
*******
*****
***
*
def out(num=5):
    result = ''
    for i in range(1, num + 1, 2):
        result += '{:^{}s}
'.format('*' * i, num)
    for j in reversed([x for x in range(1, num + 1, 2)]):
        if j == [x for x in range(1, num + 1, 2)][-1]:
            continue
        else:
            result += '{:^{}s}
'.format('*' * j, num)
    return result

def out(num=7):
    nu = 1
    k = 2
    result = ''
    while nu >= 0:
        result += int((num - nu) / 2) * ' ' + '*' * nu + '
'
        nu += k
        if nu == num:
            k = -k
    return result
1.24 输入一个正整数,判断是几位数
题目 给一个不多于5位的正整数,要求:
一、求它是几位数,
二、逆序打印出各位数字。
a = 12345
def out(content=12345):
    content = [int(i) for i in list(str(content))]
    return '他是{}位数,分别是:{}'.format(len(content), sorted(content, reverse=True))
2.1.水仙花数
如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。
例如:153 = 1^3 + 5^3 + 3^3,因此 153 就是一个水仙花数
那么问题来了,求1000以内的水仙花数(3位数)
def out(content=1000):
    lst = []
    for i in range(100, content):
        a, b, c = [int(j) for j in list(str(i))]
        if i == pow(a, 3) + pow(b, 3) + pow(c, 3):
            lst.append(i)
    return lst
2.2完全数
如果一个正整数等于除它本身之外其他所有除数之和,就称之为完全数。
例如:6是完全数,因为6 = 1+2+3;
下一个完全数是28 = 14+7+4+2+1。
求1000以下的完全数
def out(content=1000):
    result = []
    for i in range(1, content):
        temp = 0
        for j in range(1, i):
            if i % j == 0:
                temp += j
        if temp == i:
            result.append(i)
    return result
2.3  数字1-100求和
求1+2+3…+100和
print(sum(range(1, 101)))
2.4计算求1-2+3-4+5-…-100的值
计算求1-2+3-4+5-…-100的值
sum(range(1, 101, 2)) - sum(range(2, 101, 2))
2.5计算求1+2-3+4-5… …100 的值
计算求1+2-3+4-5… …100 的值
def out(content=100):
    add = 1
    sub = 0
    for i in range(1, content):
        if i % 2 == 0:
            add += i
        else:
            sub += i
    return add - sub
2.6计算 1-n 之间的所有 5 的倍数之和
定义一个函数:计算 1-n 之间的所有 5 的倍数之和,默认计算 1-100 ( n 是 一个整数)
def out(content=100):
    result = []
    for i in range(1, content):
        if i % 5 == 0:
            result.append(int(i / 5))
    return sum(result)
2.7 n个自然数的立方和
计算公式 13 + 23 + 33 + 43 + …….+ n3
实现要求:
输入 : n = 5
输出 : 225
对应的公式 : 13 + 23 + 33 + 43 + 53 = 225
def out(content=5):
    return sum([pow(i, 3) for i in range(1, content + 1)])
2.8 阶乘10!
阶乘的意思: 10!=10x9x8x7x6x5x4x3x2x1
求10!
from functools import reduce
print(reduce(lambda a, b: a * b, range(1, 11))) def out(content=10): result = 1 for i in range(1, content + 1): result *= i return result
2.9求1+2!+3!+…+10!的和
求1+2!+3!+…+10!的和
def out(content=10):
    result = []
    for i in range(1, content + 1):
        temp = 1
        for j in range(1, i + 1):
            temp *= j
        result.append(temp)
    return sum(result)
2.10求s=a+aa+aaa+aaaa+aa…a的值
求s=a+aa+aaa+aaaa+aa…a的值
def out(n=5, a=3):
    result = []
    for i in range(1, n + 1):
        result.append(int(str(a) * i))
    return sum(result)

def out(n=5, a=3):
    result = []
    for i in range(1, n + 1):
        temp = 0
        for j in range(i):
            temp += pow(10, j) * a
        result.append(temp)
    return sum(result)
2.11 斐波那契数列1、1、2、3、5、8、13 …..
已知一个数列:1、1、2、3、5、8、13、。。。。的规律为从 3 开始的每一项都等于其前两项的和,这是斐波那契数列。
求满足规律的 100 以内的所有数据
def out(n=100):
    a = 0
    b = 1
    for i in range(1, n + 1):
        yield b
        a, b = b, a + b
3.1 反转(判断对称)
如何判断一个数组是对称数组:
要求:判断数组元素是否对称。例如[1,2,0,2,1],[1,2,3,3,2,1]这样的都是对称数组
用Python代码判断,是对称数组打印True,不是打印False,如:
x = [1, 'a', 0, '2', 0, 'a', 1]
def out(x=[1, 'a', 0, '2', 0, 'a', 1]):
    count = len(x)
    state = False
    for i in range(count):
        if x[i] == x[count - i-1]:
            state = True
        else:
            return False
    return state
3.2列表切片
如果有一个列表a=[1,3,5,7,11]
问题:1如何让它反转成[11,7,5,3,1]
2.取到奇数位值的数字,如[1,5,11]
def out(a=[1, 3, 5, 7, 11]):
    result = []
    for i in range(len(a)):
        if i % 2 == 0:
            result.append(a[i])

    return list(reversed(a)), result
3.3列表大小排序
问题:对列表a 中的数字从小到大排序
a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8]
print(list(sorted([1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8])))
3.4 取出最大值最小值
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
找出列表中最大值和最小值
print(max(L1))
print(min(L1))
3.5 找出列表中单词最长的一个
a = ['hello', 'world', 'yoyo', 'congratulations']
找出列表中单词最长的一个
sorted(a, key=lambda i: len(i), reverse=True)[0]

def out(a=['hello', 'world', 'yoyo', 'congratulations']):
    result = ''
    length = 0
    for i in a:
        if len(i) > length:
            length = len(i)
            result = i
    return result
3.6 切片取出列表中最大的三个数
取出列表中最大的三个值
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
sorted(L1)[-3:]
3.7列表按绝对值排序
a = [1, -6, 2, -5, 9, 4, 20, -3] 按列表中的数字绝对值从小到大排序
print(sorted(a, key=lambda i: abs(i)))
3.8按字符串长度排序
b = ['hello', 'helloworld', 'he', 'hao', 'good']
按list里面单词长度倒叙
print(sorted(b, key=lambda i: len(i), reverse=True))

def out(a=['hello', 'world', 'yoyo', 'congratulations']):
    for i in range(len(a)):
        for j in range(len(a) - i - 1):
            if a[j] < a[j + 1]:
                a[j+1], a[j] = a[j], a[j + 1]
    return a
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
如何用一行代码得出[1, 2, 3, 5, 11, 33, 88]
L2 = [1, 2, 3, 4, 5] ,L[10:]结果是多少(报错?还是None,还是[])
sorted(L1)
[]
3.10 去重保留顺序
将列表中的重复值取出(仅保留第一个),要求保留原始列表顺序
如a=[3, 2, 1, 4, 2, 6, 1] 输出[3, 2, 1, 4, 6]
def out(a=[3, 2, 1, 4, 2, 6, 1]):
    result = []
    for i in a:
        if i not in result:
            result.append(i)
    return result
3.11 列表合并
a = [1, 3, 5, 7]
b = ['a','b','c','d']
如何得到[1, 3, 5, 7, ‘a’, ‘b’, ‘c’, ‘d’]
a+b
3.12 生成列表(列表推导式)
用一行代码生成一个包含 1-10 之间所有偶数的列表
[i for i in range(2, 11, 2)]
[i for i in range(1, 11) if i % 2 == 0]
3.13 列表成员的平方
列表a = [1,2,3,4,5], 计算列表成员的平方数,得到[1,4,9,16,25]
list(map(lambda i: i * i, a))
3.14 找出列表大于0的数
使用列表推导式,将列表中a = [1, 3, -3, 4, -2, 8, -7, 6]
找出大于0的数,重新生成一个新的列表
[i for i in a if i > 0]
list(filter(lambda i: i > 0, a)) # 非推导式
3.15统计列表有多少大于0
统计在一个队列中的数字,有多少个正数,多少个负数,如[1, 3, 5, 7, 0, -1, -9, -4, -5, 8]
print([i for i in lst if i > 0])
print([i for i in lst if i < 0])
3.16列表排除筛选
a = ['张三','张四','张五','王二'] 如何删除姓张的
[i for i in a if list(i)[0] != '']
3.17列表过滤(filter)
题1:有个列表a = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8] 使用filter 函数过滤出大于0的数
题2:列表b = ['张三', '张四', '张五', '王二'] 过滤掉姓张的姓名
print(list(filter(lambda i: i > 0, a)))
list(filter(lambda i: list(i)[0] != '', b))
3.18过滤列表中不及格学生(filter)
过滤掉列表中不及格的学生
a = [
       {'name': '张三', 'score': 66},
       {'name': '李四', 'score': 88},
       {'name': '王五', 'score': 90},
       {'name': '陈六', 'score': 56},
    ]
list(filter(lambda i: int(i.get('score')) < 60, a))
3.19找出列表中最大数出现的位置
有个列表 a = [1, 2, 3, 11, 2, 5, 88, 3, 2, 5, 33]
找出列表中最大的数,出现的位置,下标从0开始
a.index(max(a))

def out(a=[1, 2, 3, 11, 2, 5, 88, 3, 2, 5, 33]):
    result = 0
    index = None
    for i in range(len(a)):
        if a[i] > result:
            result = a[i]
            index = i
    return index
3.20找出列表中出现次数最多的元素
a = [
‘my’, ‘skills’, ‘are’, ‘poor’, ‘I’, ‘am’, ‘poor’, ‘I’,
‘need’, ‘skills’, ‘more’, ‘my’, ‘ability’, ‘are’,
‘so’, ‘poor’
]
from collections import Counter

a = [
'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I',
'need', 'skills', 'more', 'my', 'ability', 'are',
'so', 'poor'
]

dct = dict(Counter(a))
count = sorted(dct.values(), reverse=True)[0]
lst = []

for key, v in dct.items():
if v == count:
lst.append(key)
print(lst)
3.21分别统计列表中每个成员出现的次数
a = [
‘my’, ‘skills’, ‘are’, ‘poor’, ‘I’, ‘am’, ‘poor’, ‘I’,
‘need’, ‘skills’, ‘more’, ‘my’, ‘ability’, ‘are’,
‘so’, ‘poor’
]
def out(content=None):
    if content is None:
        content = [
            'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I',
            'need', 'skills', 'more', 'my', 'ability', 'are',
            'so', 'poor'
        ]
    d = {}
    for i in content:
        if i not in d:
            d[i] = 1
        else:
            d[i] += 1

    return d
3.22 列表查找元素位置
给定一个整数数组A及它的大小n,同时给定要查找的元素val,
请返回它在数组中的位置(从0开始),若不存在该元素,返回-1。
若该元素出现多次请返回第一个找到的位置
如 A1=[1, 'aa', 2, 'bb', 'val', 33]
或 A2 = [1, 'aa', 2, 'bb']
def out(content=None, word='aa'):
    if content is None:
        content = [1, 'aa', 2, 'bb', 'val', 33]
    if word in content:
        return content.index(word)
    else:
        return -1
3.23列表查找两数之和
给定一个整数数组nums 和一个目标值target ,请你在该数组中找出和为目标值的那两个整数,并返回他
们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定nums=[2,7,11,15],target=9
因为nums[0] + nums[1] =2+7 = 9
所以返回[0, 1]
def out(nums=None, target=9):
    if nums is None:
        nums = [2, 7, 11, 15, 2, 7]
    length = len(nums)
    result = []
    for i in range(length):
        for j in range(i, length):
            if nums[i] + nums[j] == target:
                print([i, j])
                result.append([i, j])
            else:
                continue
    return result
3.24二维数组取值(矩阵)
有 a = [['A', 1], ['B', 2]] ,Ï如何取出 2
a[1][1]
3.25 二维数组拼接
a = [[1,2],[3,4],[5,6]] 如何一句代码得到 [1, 2, 3, 4, 5, 6]
[j for i in a for j in i]
3.26 列表转字符串
L = [1, 2, 3, 5, 6],如何得出 ‘12356’?
''.join([str(i) for i in L])
3.27 两个列表如何得到字典
a = ['a', 'b', 'c']
b = [1, 2, 3]
如何得到 {‘a’: 1, ‘b’: 2, ‘c’: 3}
dict(zip(a,b))
3.28列表按age从小到大排序
如下列表
people = [
{'name':'yoyo', 'age': 20},
{'name':'admin', 'age': 28},
{'name':'zhangsan', 'age': 25},
]
按年龄age从小到大排序
sorted(people, key=lambda a: a['age'])
3.29列表插入元素
现有 nums=[2, 5, 7] ,如何在该数据最后插入一个数字 9 ,如何在2后面插入数字0
nums.insert(len(nums), 9)
nums.insert(nums.index(2)+1, 0)
3.30打乱列表顺序随机输出
有个列表a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
如何打乱列表a的顺序,每次得到一个无序列表
random.shuffle(a)
4.1 输出1-100除3余1 的数,结果为tuple
tuple(i for i in range(1, 101) if i % 3 == 1)
4.2 把2个元祖转字典
将 ('a', 'b', 'c', 'd', 'e') 和 (1,2, 3, 4, 5)两个tuple转成
(1, 2, 3, 4, 5)为key, ('a', 'b', 'c', 'd', 'e') 为value的字典
dict(zip((1, 2, 3, 4, 5), ('a', 'b', 'c', 'd', 'e')))
4.3 把字典的value值转成str
将字典里的值是数值型的转换为字符串,如a = {'aa': 11, 'bb': 222}
得到{'aa': '11', 'bb': '222'}
{k: str(v) for k, v in a.items()}
4.4 (1)和(1,)区别,[1]和[1,]
a = [1,2,3] 和 b = [(1),(2),(3) ] 以及 c = [(1,),(2,),(3,) ] 的区别?
int和元组,值相等但是内存地址不想等
4.5 map函数将[1,2,3,4]处理成[1,0,1,0]
map函数,有个列表a = [1, 2, 3, 4] 计算列表中每个数除以2 取出余数 得到 [1,0,1,0]
list(map(lambda i: int(i % 2), [1, 2, 3, 4]))
4.6 map函数将列表[1,2,3,4,5]转变成[1,4,9,16,25]
map函数将列表 [1,2,3,4,5] 使用python方法转变成 [1,4,9,16,25]
list(map(lambda i: i*i, [1,2,3,4,5]))
4.7 map函数a=[1,3,5],b=[2,4,6]相乘得到[2,12,30]
map函数对列表a=[1,3,5],b=[2,4,6]相乘得到[2,12,30]
list(map(lambda a, b: a * b, [1, 3, 5], [2, 4, 6]))
4.8 reduce函数计算1-100的和
reduce函数计算1-100的和
reduce(lambda a, b: a + b, range(1, 101))
4.9 reduce函数计算10!
reduce函数计算1!+2!+3!+。。。+10!
b = map(lambda x: reduce(lambda i, a: i * a, range(1, x + 1)), range(1, 11))
print(reduce(lambda i, j: i + j, b))
4.10 两个字典合并a={'A':1,'B':2},b={'C':3,'D':4}
两个字典合并a={'A':1,'B':2},b={'C':3,'D':4}
a.update(b)
print(a)
4.11 {'a':1,'b':2,'c':1} 得到 {1:['a','c'],2:['b']}
m1={'a':1,'b':2,'c':1} # 将同样的value的key集合在list里,输出{1:['a','c'],2:['b']}
def out(m1={'a': 1, 'b': 2, 'c': 1}):
    result = {}
    for k, v in m1.items():
        if v in result:
            result[v] = result[v] + [k]
        else:
            result[v] = [k]
    return result
4.12 字典按key排序d={'name':'zs','age':18,'}
d={'name':'zs','age':18,'city':'深圳','tel':'1362626627'}
字典根据键从小到大排序
dict(sorted(d.items(), key=lambda i: i))
4.13 集合(交集、差集、并集)
a = [2, 3, 8, 4, 9, 5, 6]
b = [2, 5, 6, 10, 17, 11]
1.找出a和b中都包含了的元素
2.a或b中包含的所有元素
3.a中包含而集合b中不包含的元素 a-b
print(f'1.答案:{a.intersection(b)}')
print(f'2.答案:{a.union(b)}')
print(f'3.答案:{a.difference(b)}')
5.1 有1、2、3、4组成无重复数的三位数(排列组合)
有1、2、3、4数字能组成多少互不相同无重复数的三位数?
分别打印这些三位数的组合
from itertools import permutations
[f'{i} {j} {k}' for i, j, k in permutations(list('1234'), 3)]
def out(nums='1234'):
    result = []
    for i in str(nums):
        for j in str(nums):
            for k in str(nums):
                if i != k and i != j and j != k:
                    result.append(i+j+k)
    return result
5.2 冒泡排序
a = [11, 2, 33, 1, 5, 88, 3]
冒泡排序:
依次比较两个相邻的元素,如果顺序(如从小到大、首字母从A到Z)
错误就把他们交换过来
def out(a=[11, 2, 33, 1, 5, 88, 3]):
    length = len(a)
    for i in range(length):
        for j in range(length - i - 1):
            if a[j] > a[j + 1]:
                a[j + 1], a[j] = a[j], a[j + 1]
    return a
5.3文本中每行中长度超过3的单词
在以下文本中找出 每行中长度超过3的单词:
words = "Call me Ishmael. Some years ago - never mind how long precisely - having
little or no money in my purse, and nothing particular to interest me
on shore, I thought I would sail about a little and see the watery part
of the world. It is a way I have of driving off the spleen, and regulating
the circulation. - Moby Dick"
lst = words.replace('
', ' ').split(' ')
print(list(filter(lambda i: len(str(i)) > 3, lst)))
5.4 列表数据写入txt(open读写)
有一个数据list of dict如下
a = [
{'yoyo1': '123456'},
{'yoyo2': '123456'},
{'yoyo3': '123456'},
]
写入到本地一个txt文件,内容格式如下:
yoyo1,123456
yoyo2,123456
yoyo3,123456
def out(a=None):
    if a is None:
        a = [
            {'yoyo1': '123456'},
            {'yoyo2': '123456'},
            {'yoyo3': '123456'},
        ]
    result = ''
    for i in a:
        result += ''.join(list(i.keys())) + ',' + ''.join(list(i.values())) + '
'
    with open('out.txt', 'w') as wf:
        wf.write(result)
5.5 判断邮箱程序(正则)
写一个小程序:控制台输入邮箱地址(格式为 username@companyname.com), 程序识别用户名和公司名后,将用户名和公司名输出到控制台。
要求:
校验输入内容是否符合规范(xx@yy.com), 如是进入下一步,如否则抛出提 示”incorrect email format”。注意必须以.com 结尾
可以循环“输入—输出判断结果”这整个过程
按字母 Q(不区分大小写)退出循环,结束程序
def out():
    d = {'username@companyname.com': 'complete'}
    while True:
        content = input('请输入邮箱地址: ')
        if content.lower() == 'q':
            sys.exit()
        email = re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}.com$', content)
        if email:
            if email[0] in d:
                print(email[0], d[email[0]])
            else:
                print('邮箱未在公司中')
        else:
            print('邮箱不合法')
5.6判断一个字符串的括号自否闭合(栈)
判断一个字符串的括号自否闭合(包括大小中括号)
左括号和右括号必须是一一对应
def out(content='{[{()}]()}'):
    list1 = []
    flag = True
    for i in content:
        if i == "{" or i == "[" or i == "(":
            list1.append(i)
        elif i == "}":
            if len(list1) == 0 or list1.pop() != "{":
                return False
        elif i == "]":
            if len(list1) == 0 or list1.pop() != "[":
                return False
        elif i == ")":
            if len(list1) == 0 or list1.pop() != "(":
                return False
    if len(list1) != 0:
        flag = False
    return flag
5.7 计算纯数字子串组成的单一数字(子串)
有一个纯数字组成的字符串, 返回连续单一数字子串的个数
输入字符串:“22252”
只含单一数字的子串是
1个字符:2出现4次,5出现1次
2个字符 22 出现2 次
3个字符 222 出现1 次
4个子串 0次
5个字符 0次
总共 4+1+2+1 =8
输出结果:8

示例:
输入:22252
输出:8
def out(content='22252'):
    d = {}
    temp = ''
    for i in content:
        temp += i
        d.update({temp: content.count(temp)})
    return sum(list(d.values()))
5.8 移除字符串里面的’ab’
有一个字符串列表['aababbc', 'badabcab'] 将字符串中的’ab’ 移除
比如’aababbc’ 移除里面的ab后得到abc 需继续移除ab,得到c,直到字符串中不会出现连续的ab
def out(content=None):
    if content is None:
        content = ['aababbc', 'badabcab']
    result = []
    for i in content:
        while 'ab' in i:
            i = i.replace('ab', '')
        result.append(i)
    return result
5.9看代码得结果(join用法)
x=”abc”,y=”def”,z=[“d”,”e”,”f”],
分别求出x.join(y) 和x.join(z)返回的结果
'dabceabcf'  'dabceabcf'
5.10 看代码得结果(类和继承)
阅读以下代码,打印结果是什么?

class A(object):

def __init__(self):
self.__Gender()
self.Name()

def __Gender(self):
print("A.__Gender()")

def Name(self):
print("A.Name()")

class B(A):

def __Gender(self):
print("B.__Gender()")

def Name(self):
print("B.Name()")
b = B()
答案:A.__Gender()
B.Name()
5.11 看代码得结果(闭包)
阅读以下代码,得到的结果是什么

def fun():
temp = [lambda x: i*x for i in range(4)]
return temp

for everyLambda in fun():
print(everyLambda(2))
6
6
6
6
5.12看代码得结果(列表推导式)
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))

A1 = range(10)  # range(0,10)
A2 = [i for i in A1 if i in A0]  # []
A3 = [A0[s] for s in A0]  # [1,2,3,4,5]
A4 = [i for i in A1 if i in A3]  # [1,2,3,4,5]
A5 = {i:i*i for i in A1}  # [0,1,4,9,16,25,36,49,64,81]
A6 = [[i,i*i] for i in A1]  # [[0,1],[1,1],[2,4],[3,9],[4,16],[5,25],[6,36],[7,49],[8,64],[9,81]]
5.13 看代码得结果(函数)
阅读以下代码,得到什么结果

def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print l

f(2)  # [0,1]
f(3,[3,2,1])  # [3,2,1,0,1,2]
f(3)  # [0,1,0,1,2]
5.14 看代码得结果(深拷贝和浅拷贝)
写出以下程序的输出结果

from copy import deepcopy, copy

li = [1, 2, [3, 4]]
li_sliced = li[:]
li_copied = copy(li)
li_deep_copied = deepcopy(li)

li[0] = 888
li[2][0] = 666
print(li_sliced, li_copied, li_deep_copied)  # [1, 2, [666, 4]],[1, 2, [666, 4]] ,[1, 2, [3, 4]]
5.15 map reduce filter的使用
分别使用map reduce filter 函数完成下面的任务
from functools import reduce
1.计算 1- 100 的和  # reduce(lambda a, b: a + b, range(1, 101))
2.1-10,对每个数字的平方 list(map(lambda i:i*i, range(1, 11))
3. ['a', 'ab', 'abc', 'bc', 'cd']输出含有c字符的元素,返回值是list
# list(filter(lambda i: 'c' in i, ['a', 'ab', 'abc', 'bc', 'cd']))
5.16 通过切片操作完成以下任务(切片)
有个字符串为”abcdefg.exe” 通过切片完成下面的任务
1.输出前3个字符  # [:3]
2.输出后2个字符  # [-2:]
3.倒叙输出  # [::-1]
4.间隔1个字符串输出  [::2]
5.17 根据列表数字出现次数排序去重(排序)
a=[1,2,1,2,2,2,3,4,5,6,56,7,1,3,4]
按列表中数字出现的次数,从高到低排序,并去除重复的 # sorted(set(a), reverse=True)
比如2出现了4次,排第一个位置。1出现了3次,于是可以得到:[2, 1, 3, 4, 5, 6, 7, 56]
def out(a=[1, 2, 1, 2, 2, 2, 3, 4, 5, 6, 56, 7, 1, 3, 4]):
    d = {}
    for i in a:
        if i in d:
            d[i] = d[i] + 1
        else:
            d[i] = 1
    result = list(sorted(d, key=lambda j: d[j], reverse=True))
    return result
5.18 补缺失的代码-给个路径查找文件(递归)
def print_directory_contents(sPath):
“””
这个函数接受文件夹的名称作为输入参数,
返回该文件夹中文件的路径,
以及其包含文件夹中文件的路径。
def print_directory_contents(sPath):
    path = os.path.abspath(sPath)
    for root, dirs, files in os.walk(path):
        for file in files:
            print(os.path.join(root, file))

def print_directory_contents(s_path):
    for s_child in os.listdir(s_path):
        s_child_path = os.path.join(s_path, s_child)
        if os.path.isdir(s_child_path):
            print_directory_contents(s_child_path)
        else:
            print(s_child_path)
5.19 如何判断一个字符串有没有重复字符
判断一个字符串是否包含重复字符。例如:“hello”就包含重复字符‘l’,而“world”就不包含重复字符, 有重复打印True, 没重复打印False
def out(content='hello'):
    result = ''
    state = True
    for i in content:
        if i in result:
            return False
        else:
            result += i
            state = True
    return state
5.20 找出一个字符串中子串不含有重复字符的最长子串(子串)
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
示例1:
输入:” abcabcbb” 输出: 3
解释:因为无重复字符的最长子串是”abc”, 所以其长度为3。
示例2:
输入: “bbbbb”” 输出: 1
解释:因为无重复字符的最长子串是”b”, 所以其长度为1。
示例3:
输入: “ pwwkew” 输出: 3
解释:因为无重复字符的最长子串是”wke”‘, 所以其长度为3。
请注意,你的答案必须是子串的长度,”pwke”是一个子序列,不是子串。
def out(content='abcabcbb'):
    result = ''
    lst = []
    for i in content:
        if i not in result:
            result += i
        else:
            lst.append(result)
            result = ''
    if result not in lst:
        lst.append(result)

    sort_lst = sorted(lst, key=lambda length: len(str(length)), reverse=True)

    return sort_lst[0], len(sort_lst[0])
5.21 一个字符串中所有子串是回文的次数(子串)
回文是指正序(从左向右)和倒序(从右向左)读都是一样的。
例如:121 ,abcdedcba,123321等都是回文
这种的字符串“ABCABADCSABBAUYIIYU”找出回文出现的次数
子串回文是:’BB’, ‘II’,’ABA’,’ABBA’, ‘YIIY’,’UYIIYU’ 总共有6个
def out(content='ABCABADCSABBAUYIIYU'):
    lst = []
    for i in range(2, len(content) + 1):
        for j in range(len(content) - i + 1):
            # 生成的组合
            new_s = content[j:j + i]
            lst.append(new_s)
    return [i for i in lst if i == i[::-1]]
5.22 找出一个列表中,所有出现的连续数(栈)
找出一个列表中,所有出现的连续数字,如列表a=[1,2,3,8,6,7,5,10,16,98,99,100,101],不考虑数字的顺序
连续的数字是指:123, 456, 78 这种,可以是连续的2个,也可以是多个,135 这种是不连续的。
于是可以知道连续的数字是[1,2,3],[5,6,7,8], [98,99,100,101]
def out(a=[1, 2, 3, 8, 6, 7, 5, 10, 16, 98, 99, 100, 101]):
    s = []
    for i in sorted(set(a)):
        if len(s) == 0 or s[-1] + 1 == i:
            s.append(i)
        else:
            if len(s) >= 2:
                print(s)
            s = [i]
    if len(s) >= 2:
        print(s)

给定一个字符串数组,将字母异位词组合在一起。

字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

lst = ["eat", "tea", "tan", "ate", "nat", "bat"]

dct = {}
for words in lst:
    k = str(sorted(words))
    if k not in dct:
        dct[k] = [words]
    else:
        dct[k] = dct[k] + [words]
print([v for v in dct.values()])

现在数据:[{tagName: 'p'}, {tagName: 'div'}, {tagName: 'p'}, ....],
请统计出现次数 TOP 1 的 tagName。

lst = [{'tagName': 'p'}, {'tagName': 'div'}, {'tagName': 'p'}]
dct = {}
for i in lst:
    k = i['tagName']
    if k not in dct:
        dct[k] = 1
    else:
        dct[k] = dct[k] + 1
print(sorted(dct, key=lambda key: dct[key], reverse=True)[0])
原文地址:https://www.cnblogs.com/qianmaoliugou/p/15239215.html