'Python to sort tag with different attributes
I have a list from links = set(soup.findAll('a')), now I want to sort them, but links = sorted(links) got error, what can I sort it?
The original list and any else attributes:
<a href="//weathernews.jp/typhoon/">台風</a>
<a class="list" href="https://weathernews.jp/s/topics/201809/190035/?fm=tp_index"></a>
<a class="list" href="https://weathernews.jp/s/topics/201809/130155/?fm=tp_index"></a>
<a href="//weathernews.jp/warning/">警報・注意報</a>
<a class="list" href="https://weathernews.jp/s/topics/201809/140125/?fm=tp_index"></a>
<a class="list" href="https://weathernews.jp/s/topics/201809/170145/?fm=tp_index"></a>
I want to sort it to
<a class="list" href="https://weathernews.jp/s/topics/201809/190035/?fm=tp_index"></a>
<a class="list" href="https://weathernews.jp/s/topics/201809/170145/?fm=tp_index"></a>
<a class="list" href="https://weathernews.jp/s/topics/201809/140125/?fm=tp_index"></a>
<a class="list" href="https://weathernews.jp/s/topics/201809/130155/?fm=tp_index"></a>
<a href="//weathernews.jp/typhoon/">台風</a>
<a href="//weathernews.jp/warning/">警報・注意報</a>
Solution 1:[1]
I would suggest you to first map the links to strings and then sort it.
links = soup.findAll('a')
links = map(str, links)
links = sorted(links)
OR
Simply,
links = sorted(map(str, links))
Solution 2:[2]
I got it with this
links = sorted(links, key=lambda x: str(x), reverse=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | mikezang |
