当前位置:首页 » 数据分析 » 正文

浅谈python元素如何去重,去重后如何保持原来元素的顺序不变

看: 924次  时间:2020-08-10  分类 : 数据分析

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元素如何去重,去重后如何保持原来元素的顺序不变就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

标签:urllib  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!