简体   繁体   English

Python:按长度比较列表的列表并创建大小相等的新列表

[英]Python : compare lists of a list by length and create new lists of equal sizes

i have a big list that consists of multiple lists of arbitrary lengths. 我有一个大列表,其中包含多个任意长度的列表。 I want to compare each list length and create new lists of equal sizes. 我想比较每个列表的长度并创建相等大小的新列表。 For example, 例如,

biglist = [['x','y','z'],['a','b'],['d','f','g'],...,['r','e','w','q','t','u','i']]
expected_list= [['a','b'],[['x','y','z'],['d','f','g']],....,['r','e','w','q','t','u','i']] 

I am new to python. 我是python的新手。 can anyone suggest me a less expensive method to do the above process. 有人可以建议我用一种较便宜的方法来完成上述过程吗? Thanks in advance. 提前致谢。

It looks like you want to groupby a list by its element len s: 看起来您想按其元素len s对列表进行groupby

>>> biglist = [['x', 'y', 'z'], ['a', 'b'], ['d', 'f', 'g'], ['r', 'e', 'w', 'q', 't', 'u', 'i']]
>>> expected_list = [list(b) for a, b in itertools.groupby(sorted(biglist, key=len), len)]
>>> expected_list
[[['a', 'b']], [['x', 'y', 'z'], ['d', 'f', 'g']], [['r', 'e', 'w', 'q', 't', 'u', 'i']]]

May I suggest using itertools groupby function? 我可以建议使用itertools groupby函数吗?

import itertools


biglist = [['x','y','z'],['a','b'],['d','f','g'],['r','e','w','q','t','u','i']]

print(list(list(i[1]) for i in itertools.groupby(sorted(biglist, key=len), len)))

Which outputs 哪个输出

[[['a', 'b']], [['x', 'y', 'z'], ['d', 'f', 'g']], [['r', 'e', 'w', 'q', 't', 'u', 'i']]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何比较 python 中的 N 个列表并创建具有唯一元素的新列表 - How to compare N lists in python and create a new list with unique elements 将列表元素与列表列表元素进行比较,并有条件地创建新列表 - compare elements of list to elements of list of lists and conditionally create new lists 不等长列表上的Python映射 - Python map on not equal length lists 在 python 中创建一个列表列表,其中包含单词的长度和计数 - Create a list of lists in python with length and count for words 比较两个python列表,并将较短的列表扩展为较长的列表的长度 - Compare two python lists and expand the shorter list to the length of the longer list 加入两个不同大小的列表以在 python 中创建一个新字典 - joining two lists of different sizes to create a new dictionary in python 从列表的python列表和带有列表的列创建新的pandas数据框 - Create a new pandas dataframe from a python list of lists with a column with lists 在与最长列表长度相同的列表列表中创建一个新列表 - Create a new list in a list of lists that has the same length as the longest one 比较两个不同大小的列表列表并创建一个新列表 - Compare Two different size list of lists and create a new list 在python中使用集合和列表来创建一个新列表 - Use sets and lists in python to create a new list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM