How can I sort list lines by time if the times are in different locations in the line?

PW1990

I have been making a program that sorts lines of weather data. The lines of data are needing to be sorted in order of time. I am receiving a list of weather lines that are formatted slightly differently to each other, and depending on the weather behaviour and how fast the changes are occurring the line will start with FM or BECMG.

I am able to sort lines of weather where the time listed is in the same index location each time (index [0]). for example:

FM131200 20010KT 5000 SHOWERS OF LIGHT RAIN SCT006 BKN010 

and

FM131400 20010KT 9999 SHOWERS OF LIGHT RAIN SCT006 FEW030

From the two examples above, the first one's time is displaying the 13th day of the month, at 12:00. In the second one it's the 14th day of the month and 14:00. This format is fine because the time index is in the same index on both, but if I have a situation like below, my sorting doesn't work.

FM131400 20010KT 9999 SHOWERS OF LIGHT RAIN SCT006 BKN010

and

BECMG 1315/1317 27007KT 9999 SHOWERS OF LIGHT RAIN SCT020 BKN030

From the examples above, the first line is obviously the same as the previous examples but the second one is different in location (index [1]) and format. The time in the second line is the 13th day of the month at 15:00.

I have this as an example for how I am sorting them chronologically for now, but it only works if the line has the time at index [0].

import re

total_print = ['\nBECMG 1315/1317 27007KT 9999 SHOWERS OF LIGHT RAIN SCT020 BKN030', '\nFM131200 20010KT 9999 SHOWERS OF LIGHT RAIN SCT006 BKN010',
               '\nFM131400 20010KT 9999 SHOWERS OF LIGHT RAIN SCT006 BKN010']

data = {
    'other': [], # anything with FM or BECMG
}

for line in total_print:
    key = 'other'
    data[key].append(line)

final = []
data['other'] = sorted(data['other'], key=lambda x: x.split()[0])

for lst in data.values():
    for line in lst:
        final.append('\n' + line[1:])

print(' '.join(final))

The lines are supplied in a random order and are sometimes all starting with BECMG or all with FM and sometimes both. So I need to find a way to sort them no matter how they come.

How can I sort the lines in chronological order regardless of whether the line is starting with FM or BECMG?? Should I use Regex and isolate the times?? Can anyone help with this please, I am stuck?

Ron Serruya

You can extract the times using regex, and then use this time as the "key" to sort on

import re

pattern = r"((?<=FM)\d{6})|(?<=BECMG )\d{4}"
matcher = re.compile(pattern)

data = ['FM131200 20010KT 5000 SHOWERS OF LIGHT RAIN SCT006 BKN010 ',
 'FM131400 20010KT 9999 SHOWERS OF LIGHT RAIN SCT006 FEW030',
 'BECMG 1315/1317 27007KT 9999 SHOWERS OF LIGHT RAIN SCT020 BKN030',
 'FM131400 20010KT 9999 SHOWERS OF LIGHT RAIN SCT006 BKN010']

print(sorted(data, key=lambda item: matcher.search(item).group()))

This will print:

['FM131200 20010KT 5000 SHOWERS OF LIGHT RAIN SCT006 BKN010 ',
 'FM131400 20010KT 9999 SHOWERS OF LIGHT RAIN SCT006 FEW030',
 'FM131400 20010KT 9999 SHOWERS OF LIGHT RAIN SCT006 BKN010',
 'BECMG 1315/1317 27007KT 9999 SHOWERS OF LIGHT RAIN SCT020 BKN030']

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

How can I tell if the list order changed when I sort by different properties of the list?

How Can I Extend ASP.NET Core 2.0's Roles to Handle Different Permissions at Different Locations?

Prolog How can I sort a list like this

How can I sort (Custom Sort) list of Dictionary entry by value

How can I sort a list of file names by some substring of the name?

How can I sort a list of Employees by the SortOrder of their Roles?

How can I sort my List in C# to the Month?

How can I print 2 lines if the second line contains the same match as the first line?

How can I monitor different OpenMP threads in real time?

How to copy elements in a list different number of times?

How would I be able display the title in two lines with a different font size for each line?

C# - How can I initilalize List<string[]> in the same line

How can I expand this list comprehension into a multi-line for loop?

How can I add line numbers to a textarea using an ordered list?

How to print a list of lists in different lines?

How can I convert a series of keys to locations with a Pandas index?

how to sort lines of a file in c by looking one of the attributes in the line?

How can I insert a new line into a text file into every other 2 lines?

How can I use `\sort ...`?

How can I sort Week

How can I loop through a string two lines at a time (two carriage returns per iteration)?

How can I sort this list by column which I need to print to a .csv

How can I sort a nested array representing different data sets in google apps script?

How can I calculcate mean times in pandas?

How Can I parse and convert Dates & Times?

how can I sort a field form an Endnote Export File format where the Line contains GRAZ in the address as first line?

How can I generate an SQL where clause from a filtered list of lines in a file?

How can I get a full process list in solaris, without truncated lines?

How to extract different elements of a list at the same time

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo