Home > OS >  Change the output to ascending instead of descending order in Python
Change the output to ascending instead of descending order in Python

Time:12-08

I have a function that loops forever and retrives the latest article written from a webpage and parses it on a Streamlit local website. For now the output goes in a descending order and the latest article gets printed last. Is there a way to reverse it, to get the latest on top?

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())

I have tried to store it inside a list then .sort() before parsing it out.

list = []

async for message_ in websocket:
   data = json.loads(message_)
   list.append(data)
   list.sort()
   st.write(list)

CodePudding user response:

Python's .sort() method is for sorting a list by eg. alphabetical or numeric order. In your case, you just want to reverse the list, so you can use .reverse()

list = []

async for message_ in websocket:
   data = json.loads(message_)
   list.append(data)

list.reverse()
st.write(list)

Note that I'm only writing the list to the stream at the end, instead of each time.

CodePudding user response:

If you already have the data in the list you could just

st.write(list.reverse())
  • Related