“Python meratakan daftar daftar” Kode Jawaban

Python cara meratakan daftar

flat_list = [item for sublist in l for item in sublist]
Talented Thrush

Daftar datar Python dari daftar daftar

flat_list = [item for sublist in l for item in sublist]

#which is equivalent to this 
flat_list = []
for sublist in l:
    for item in sublist:
        flat_list.append(item)
Batman

Ratakan daftar Python

flattened = [val for sublist in list_of_lists for val in sublist]
Disturbed Dogfish

Ratakan daftar Python daftar

# idiomatic python

# using itertools
import itertools

list_of_list = [[1, 2, 3], [4, 5], [6]]
chain = itertools.chain(*images)

flattened_list = list(chain)
# [1, 2, 3, 4, 5, 6]
Adventurous Alligator

Daftar perataan Python

itertools.chain.from_iterable(factors)
Blushing Butterfly

Python meratakan daftar daftar

from collections.abc import Iterable

def flatten(l):
    for el in l:
        if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el
Strange Stag

Jawaban yang mirip dengan “Python meratakan daftar daftar”

Pertanyaan yang mirip dengan “Python meratakan daftar daftar”

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya