[英]Grouping every nth lists of list in Python
我试图在 python 中将每 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']]
我希望现在的输出变成:
[['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']]
有任何想法吗? 谢谢!
您可以执行以下操作:
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)]
输出在哪里:
[['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']]
关于我合并列表的方式的解释可在带有空列表解释的嵌套列表总和中找到
列表理解的解释可在https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ 获得
我会使用减少,
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']]
没有列表理解:
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)
输出
[['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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.