Quando voglio spiegare una lista, ho trovato un modo come di seguito:Cosa fa la somma della funzione integrata con sum (list, [])?
>>> a = [[1, 2], [3, 4], [5, 6]]
>>> a
[[1, 2], [3, 4], [5, 6]]
>>> sum(a, [])
[1, 2, 3, 4, 5, 6]
Non so cosa sia successo in queste righe, e the documentation stati:
sum(iterable[, start])
Sums
start
and the items of aniterable
from left to right and returns the total.start
defaults to0
. The iterable's items are normally numbers, and thestart
value is not allowed to be a string.For some use cases, there are good alternatives to
sum()
. The preferred, fast way to concatenate a sequence of strings is by calling''.join(sequence)
. To add floating point values with extended precision, seemath.fsum()
. To concatenate a series of iterables, consider usingitertools.chain()
.New in version 2.3.
Non è vero pensi che l'inizio dovrebbe essere un numero? Perché lo []
può essere scritto qui?
(sum(a, []))
'sum' è in realtà codificato per rifiutare le stringhe. Fornisce l'errore 'TypeError: sum() non può sommare le stringhe [usa '' .join (seq) invece ' – interjay
@interjay sì, appena rilevato che durante la modifica dell'OP e risolto di conseguenza – jonrsharpe
Buona risposta, imparato qualcosa di nuovo:) – Noxeus