浅谈python元素如何去重,去重后如何保持原来元素的顺序不变
时间:2021-04-30 10:11:22|栏目:Python代码|点击: 次
python列表元素去重后如何保持原来的顺序不变
原列表:
list1 = [1,2,1,4,9,3,5,2,6,7,3,1,6,8,4,0]
去重,使用集合set来去重:
list2 = list(set(list1)
set去重得到的list2默认按升序进行排序:
list2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
使list2按照list1元素出现的顺序进行排序(也就是原来的顺序):
list2.sort(key = list1.index)
此时,list2 = [1, 2, 4, 9, 3, 5, 6, 7, 8, 0]
具体的实现过程如下:

补充拓展:python爬取链接去重
我就废话不多说了,直接上代码吧!
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
pages = set()
def getLinks(pageUrl):
global pages
html = urlopen("http://en.wikipedia.org"+pageUrl)
bsObj = BeautifulSoup(html)
for link in bsObj.findAll("a",href = re.compile("^(/wiki/)")):
if 'href' in link.attrs:
if link.attrs['href'] not in pages:
#遇到新的页面
newPage = link.attrs['href']
print(newPage)
pages.add(newPage)
getLinks(newPage)
getLinks("")
上一篇:python requests.post带head和body的实例
栏 目:Python代码
本文标题:浅谈python元素如何去重,去重后如何保持原来元素的顺序不变
本文地址:http://www.codeinn.net/misctech/111696.html






