如何将Streamlit中WebSocket获取的文章输出改为升序(最新置顶)
问题描述
我编写了一个通过WebSocket持续获取网页最新文章并在本地Streamlit网站展示的函数,目前最新文章显示在最后(降序排列),想调整为升序让最新内容置顶。
原实现代码
import streamlit as st import asyncio import websockets import json async def main(): async with websockets.connect(website) as websocket: async for message_ in websocket: data = json.loads(message_) st.write(data) asyncio.new_event_loop().run_until_complete(main())
尝试过的代码
list = [] async for message_ in websocket: data = json.loads(message_) list.append(data) list.sort() st.write(list)
解决方案
方法1:按接收顺序直接置顶最新内容
不需要额外排序,直接把新获取的文章插入列表头部,这样列表天然就是最新内容在前的顺序:
import streamlit as st import asyncio import websockets import json async def main(): articles = [] # 避免用`list`作为变量名,会覆盖Python内置类型 async with websockets.connect(website) as websocket: async for message_ in websocket: data = json.loads(message_) articles.insert(0, data) # 将新文章插入列表头部 st.write(articles) asyncio.new_event_loop().run_until_complete(main())
方法2:按文章时间字段精准排序
如果你的文章数据包含发布时间字段(比如publish_time),可以基于该字段排序,确保真正最新发布的内容置顶:
import streamlit as st import asyncio import websockets import json async def main(): articles = [] async with websockets.connect(website) as websocket: async for message_ in websocket: data = json.loads(message_) articles.append(data) # 按发布时间降序排序,最新的排在最前面 articles.sort(key=lambda x: x['publish_time'], reverse=True) st.write(articles) asyncio.new_event_loop().run_until_complete(main())
内容的提问来源于stack exchange,提问作者Snuskbetty
相关产品推荐
相关产品推荐

