python常用功能模块

1、从 List 中删除重复元素的N种方法

# 方式1:遍历列表,生成新列表保存不重复的元素
def duplicate_removal(list_name):
    """
    列表去重
    :param list_name: 一个有重复元素的列表
    :return: 去重的列表
    """
    # 方式1:遍历复杂模式
    new_list = []
    for i in list_name:
        if i not in new_list:
            new_list.append(i)
    return new_list
    # 方式2:列表推导式模式
    [new_list.append(x) for x in list_name if x not in new_list]
    return new_list
    # 方式3:使用set(),最流行。缺点:使用过后列表中元素的顺序不再与原来的一致了。
    return list(set(list_name))
    # 方式4:在列表推导式的基础上利用枚举来去除重复元素。通过检查元素是否已经在列表中存在从而将其略过。
    new_list = [i for n, i in enumerate(list_name) if i not in list_name[:n]]
    return new_list
    # 方式5:最快的方法。它先是将列表中的重复项移除并返回一个字典,最后转换成列表。这种方法对于字符串也可以进行处理。
    from collections import OrderedDict
    new_list = list(OrderedDict.fromkeys(list_name))
    return new_list

# 还有其它方法实现,但有点复杂就不写了。

2、删除字符串中间的空格

# 方式1
a = 'Hello World'
a.replace('','')
# 方式2
a = ''.join(a.split())
print(a)

3、对path和网址字符串的操作

# 方式1
path = "K:/Project/FilterDriver/DriverCodes/hello.txt"
url = 'https://www.sina.com/y/2/index.html'
print(path.split('/')[-1])    # 取得最后一个'/'后的文件名:hello.txt
print(url.split('/')[-1])     # 取得最后一个'/'后的文件名:index.html
# 方式2
import os. path
print(os.path.basename(filePath))       # 取得最后一个'/'后的文件名:hello.txt
print(os.path.basename(url))            # 取得最后一个'/'后的文件名:index.html

print(url[0:url.rfind('/') + 1])        # 用切片,截取最后一个'/'前面的所有内容。

4、urllib处理URL的标准接口,例如实现URL各部分的抽取、合并以及链接转换

from urllib.parse import urlparse
# 该方法可以实现URL的识别和分段
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
# 这里我们利用urlparse()方法进行了一个URL的解析。首先,输出了解析结果的类型,然后将结果也输出出来。
print(type(result), result)

# ParseResult(scheme='https', netloc='www.baidu.com', path='/admin/s', params='', query='user=test', fragment='')

5、continue不适合在while循环中使用

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值