Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
How to add an extra middle step into a list comprehension?

Let's say I have a typing.List[str] object containing timestamps in "HH:mm" format, e.g.

timestamps = ["22:58", "03:11", "12:21"]

I want to convert it to a typing.List[int] object with the "number of minutes since midnight" values for each timestamp:

converted = [22*60+58, 3*60+11, 12*60+21]

... but I want to do it in style and use a single list comprehension to do it. A (syntactically incorrect) implementation that I naively constructed was something like:

def timestamps_to_minutes(timestamps: typing.List[str]) -> typing.List[int]:
    return [int(hh) * 60 + int(mm) for ts in timestamps for hh, mm = ts.split(":")]

... but this doesn't work because for hh, mm = ts.split(":") is not a valid syntax.

What would be the valid way of writing the same thing?

To clarify: I can see a formally satisfying solution in the form of:

def timestamps_to_minutes(timestamps: typing.List[str]) -> typing.List[int]:
    return [int(ts.split(":")[0]) * 60 + int(ts.split(":")[1]) for ts in timestamps]

... but this is highly inefficient and I don't want to split the string twice.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You could use an inner generator expression to do the splitting:

[int(hh)*60 + int(mm) for hh, mm in (ts.split(':') for ts in timestamps)]

Although personally, I'd rather use a helper function instead:

def timestamp_to_minutes(timestamp: str) -> int:
    hh, mm = timestamp.split(":")
    return int(hh)*60 + int(mm)

[timestamp_to_minutes(ts) for ts in timestamps]

# Alternative
list(map(timestamp_to_minutes, timestamps))
over 4 years ago · Santiago Trujillo Denunciar

0

If you don't want to split string twice you can use := assignment operator:

timestamps = [int((s := t.split(":"))[0]) * 60 + int(s[1]) for t in timestamps]
print(timestamps)

Prints:

[1378, 191, 741]

Alternative:

print([int(h) * 60 + int(m) for h, m in (t.split(":") for t in timestamps)])

Prints:

[1378, 191, 741]

Note: := is a feature of Python 3.8+ commonly referred to as the "walrus operator". Here's the PEP with the proposal.

over 4 years ago · Santiago Trujillo Denunciar

0

Your initial pseudocode

[int(hh) * 60 + int(mm) for ts in timestamps for hh, mm = ts.split(":")]

is pretty close to what you can do:

[int(hh) * 60 + int(mm) for ts in timestamps for hh, mm in [ts.split(':')]]

In Python 3.9, expressions like this were optimized so that creating a single-element array inside a comprehension just to access its single element immediately is as fast as a simple assignment.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda