简体   繁体   中英

Grouping every nth lists of list in Python

I am attempting to group the every 4 lists into one list in python. Whenever I scrape the data it returns to look like this:

[['Ethnicity /Sex'], ['DOB /Age'], ['Booking Date'], ['Release Date'], ['AMERICAN (US)', 'FEMALE'], ['04/07/1968', '52 years old'], ['1/2/2020 4:34 AM'], ['1/2/2020 8:47 PM']]

I would like for the output to now become:

[['Ethnicity /Sex', 'DOB /Age', 'Booking Date', 'Release Date'], ['AMERICAN (US)', 'FEMALE', '04/07/1968', '52 years old', '1/2/2020 4:34 AM', '1/2/2020 8:47 PM']]

Any ideas? Thanks!

You could do the following:

l = [['Ethnicity /Sex'], ['DOB /Age'], ['Booking Date'], ['Release Date'], ['AMERICAN (US)', 'FEMALE'], ['04/07/1968', '52 years old'], ['1/2/2020 4:34 AM'], ['1/2/2020 8:47 PM']]
res = res = [sum(l[i:i+4], []) for i in range(0, len(l), 4)]

Where the output is:

[['Ethnicity /Sex', 'DOB /Age', 'Booking Date', 'Release Date'], ['AMERICAN (US)', 'FEMALE', '04/07/1968', '52 years old', '1/2/2020 4:34 AM', '1/2/2020 8:47 PM']]
  1. An explanation on the way I merge the lists is available at Sum of Nested List with Empty List Explanation

  2. An explanation of list comprehension is available at https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/

I'd use reduce,

import functools
l = [['Ethnicity /Sex'], ['DOB /Age'], ['Booking Date'], ['Release Date'], ['AMERICAN (US)', 'FEMALE'], ['04/07/1968', '52 years old'], ['1/2/2020 4:34 AM'], ['1/2/2020 8:47 PM']]
[functools.reduce(list.__add__, l[:4])] + [functools.reduce(list.__add__, l[4:])] # [['Ethnicity /Sex', 'DOB /Age', 'Booking Date', 'Release Date'], ['AMERICAN (US)', 'FEMALE', '04/07/1968', '52 years old', '1/2/2020 4:34 AM', '1/2/2020 8:47 PM']]

without list comprehensions:

lst = [['Ethnicity /Sex'], ['DOB /Age'], ['Booking Date'], ['Release Date'], 
       ['AMERICAN (US)', 'FEMALE'], ['04/07/1968', '52 years old'], ['1/2/2020 4:34 AM'], ['1/2/2020 8:47 PM']]

res = []
while lst:
    res.append(sum(lst[:4], []))
    lst = lst[4:]

print(res)

output

[['Ethnicity /Sex', 'DOB /Age', 'Booking Date', 'Release Date'], ['AMERICAN (US)', 'FEMALE', '04/07/1968', '52 years old', '1/2/2020 4:34 AM', '1/2/2020 8:47 PM']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM