web-dev-qa-db-fra.com

Python compréhension de la liste pour rejoindre la liste des listes

Donné lists = [['hello'], ['world', 'foo', 'bar']]

Comment puis-je transformer cela en une seule liste de chaînes?

combinedLists = ['hello', 'world', 'foo', 'bar']

37
congusbongus
lists = [['hello'], ['world', 'foo', 'bar']]
combined = [item for sublist in lists for item in sublist]

Ou:

import itertools

lists = [['hello'], ['world', 'foo', 'bar']]
combined = list(itertools.chain.from_iterable(lists))
82
Nicolas
from itertools import chain

combined = [['hello'], ['world', 'foo', 'bar']]
single = [i for i in chain.from_iterable(combined)]
4
akira