网络编程
位置:首页>> 网络编程>> Python编程>> 浅谈python元素如何去重,去重后如何保持原来元素的顺序不变

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

作者:Mr_老冷  发布时间:2023-03-07 19:39:32 

标签: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元素如何去重,去重后如何保持原来元素的顺序不变

补充拓展: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("")

来源:https://blog.csdn.net/codingforhaifeng/article/details/80363867

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com