Python中list的一些比较有用的案例

参加了公司内部的建模比赛,虽然因为水平太菜初赛就没通过,不过也写了将近500行代码,其中有一些代码个人感觉还是比较有用的,记录一下,以备以后使用
1、计算每个元素在内容(字符串)中的个数,并根据数量把元素对应的值(这里用了指定值,也就是ywlx1和ywlx2)放入list中,如果有ywlx2就用extend,没有的话就用append

def get_in_list(str, content, list, ywlx1, ywlx2=''):
    '''计算每个str在content中的个数,并根据数量把ywlx放入list中'''
    if ywlx2 == '':
        num = content.count(str)
        for i in range(0, num):
            list.append(ywlx1)
    else:
        num = content.count(str)
        for i in range(0, num):
            list.extend([ywlx1,ywlx2])
    return list

2、把content中不需要的元素去除,这里的wrong_list中就是包含不需要元素的列表

def remove_wrongstr(yw_content):
    '''把字符串中有误导性的单词去除'''
    for wrongstr in wrong_list:
        if wrongstr in yw_content: yw_content = yw_content.replace(wrongstr, '')
        else: continue
    return yw_content

3、获取业务类型列表中每个元素的个数并转为字典,key是业务类型,value是个数

def return_dict(ywlx_list):
    '''获取业务类型列表中每个元素的个数并转为字典,key是业务类型,value是个数'''
    d = {}
    for i in ywlx_list:
        d[i] = ywlx_list.count(i)
    return d

4、判断一段文字中是否出现过列表中的元素

def list_str_judge(yw_content, list):
    '''判断一段文字中是否出现过列表中的元素'''
    for i in list:
        if i in yw_content: return 1
        else:continue
    return 0

5、贪心算法(我自创的,其实根本就不能说是算法。。。):分向前贪心和向后贪心,目的是把不包含关键字的列表元素向有关键字的元素靠拢,组合成新的元素并放入新列表中

def tanxin(content_list):
    '''贪心算法:分向前贪心和向后贪心,目的是把不包含关键字的列表元素向有关键字的元素靠拢,组合成新的元素并放入新列表中'''
    new_content_list = []
    #向后贪心
    if list_str_judge(content_list[0], action_list):
        new_string = content_list[0]
        for i in range(1, len(content_list)):
            if not list_str_judge(content_list[i], action_list):
                new_string = new_string + ',' + content_list[i]
                if i == len(content_list)-1:
                    new_content_list.append(new_string)
            else:
                new_content_list.append(new_string)
                new_string = content_list[i]
                if i == len(content_list)-1 and list_str_judge(content_list[i], action_list):
                    new_content_list.append(content_list[i])
    #向前贪心
    else:
        new_string = content_list[0]
        for i in range(1, len(content_list)):
            if not list_str_judge(content_list[i], action_list):
                new_string = new_string + ',' + content_list[i]
            else:
                new_string = new_string + content_list[i]
                new_content_list.append(new_string)
                if i != len(content_list)-1:
                    new_string = content_list[i-1]
    return new_content_list

6、把字符串拆分,拆分关键字包括:,。||

def string_split(string):
    '''把字符串拆分,拆分关键字包括:,。||'''
    split_list = re.split("[,,。|]", string)
    return split_list

7、把列表中的元素去重

def quchong(list1):
    '''把列表中的元素去重'''
    list2 = []
    for i in list1:
        if i not in list2:
            list2.append(i)
        else: continue
    return list2

猜你喜欢

转载自blog.csdn.net/weixin_42029733/article/details/86536360