سؤال

So, just typing in python flatten list into stack-overflow/google brings back a huge number of duplicate results. I have tried all of them, and none apply in this specific instance.

I am getting back a database result set from pyodbc which gives me a data structure that I can coerce to a list of lists. The first element (first column) in each row returned is in the form "a.b.c". I would like it to be "a", "b", "c". My first instinct was to split on period, which I did.

Before:

[["a.b.c", "d", 1], ["e.f.g", "h", 2], ... ] # rows left out for brevity

After:

# unfortunately, split returns a list, which then gets nested
[[["a", "b", "c"], "d", 1], [["e", "f", "g"], "h", 2], ... ]

However, what I'd like to see is:

[["a", "b", "c", "d", 1], ["e", "f", "g", "h", 2], ... ]

I tried the previous solutions on stack overflow for flattening a list, but while everyone mentions nested lists, no one says how to flatten only the nested lists.

I have tried:

from itertools import chain
for row in rows:
    row = list(chain(row)) # python won't allow modifications in a loop

and

rows = [list(chain(row)) for row in rows]

I imagine there must be a way, perhaps with yield, to do something like:

for row in rows:
    row = row[0].append(row[1:]) # but this doesn't work either

I don't know how to modify the inner lists in a list of lists. If there is a better way than what I've tried so far, I'd love to hear it. Thanks in advance for your help.

هل كانت مفيدة؟

المحلول

How about:

>>> s = [["a.b.c", "d", 1], ["e.f.g", "h", 2]]
>>> [k[0].split('.') + k[1:] for k in s]
[['a', 'b', 'c', 'd', 1], ['e', 'f', 'g', 'h', 2]]

This takes the list that split returns after acting on the first element and adds it to a list consisting of the rest of them.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top