[英]How to get a sorted list from a list which contains many list that have already been sorted?
For example, I have a list with many many elements 例如,我有一个包含许多元素的列表
x = [[1, 2, 3], [3, 4, 5],[2, 3, 4], [4, 7, 8], ...]
each element has already sorted. 每个元素已经排序。
How can I get a list named y
that is from x
's elements and sorted it? 如何从x
的元素中获取名为y
的列表并对其进行排序?
If I understand your question correctly, you should look into heapq.merge
: 如果我正确理解了您的问题,则应查看heapq.merge
:
>>> import heapq
>>> lists = x = [[1, 2, 3], [3, 4, 5], [2, 3, 4], [4, 7, 8]]
>>> list(heapq.merge(*lists))
[1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 7, 8]
Here is a simple solution without any library: 这是一个没有任何库的简单解决方案:
x = [[1,2,3], [3,4,5], [2,3,4], [4,7,8]]
print(sorted([item for sublist in x for item in sublist]))
Returns: [1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 7, 8]
返回: [1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 7, 8]
If you just want to sort use sorted
,try this 如果您只想使用sorted
,请尝试此操作
x = [[1, 2, 3], [3, 4, 5],[2, 3, 4], [4, 7, 8]]
y = sorted(x)
print y
If you want to get all elements in sorted way,try this 如果要以排序方式获取所有元素,请尝试此操作
x = [[1, 2, 3], [3, 4, 5],[2, 3, 4], [4, 7, 8]]
y = sorted([item for sublist in x for item in sublist])
print y
You need a "merge" operation: just start with two lists and keep taking the element that is smaller; 您需要执行“合并”操作:仅从两个列表开始,并保留较小的元素; when one list is completed copy the eventually remaining elements from the other one... 当一个列表完成后,从另一个列表中复制最终剩余的元素...
def merge(A, B):
result = []
ia = ib = 0
while ia < len(A) and ib < len(B):
if a[ia] < b[ib]:
result.append(A[ia])
ia += 1
else:
result.append(B[ib])
ib += 1
# copy "tail"
while ia < len(A):
result.append(A[ia])
ia += 1
while ib < len(B):
result.append(B[ib])
ib += 1
return result
If you have a collection of N
lists just merge them in pairs and you will end up with half of them. 如果您有N
列表的集合,则将它们成对合并,最后将得到其中的一半。 Repeat until you get just one list. 重复直到您只得到一个列表。
I am going to give you some pointers. 我将给您一些指示。
First, define a function merge(x, y)
that gets two sorted lists and returns a combined sorted list. 首先,定义一个函数merge(x, y)
,该函数获取两个排序列表并返回一个合并的排序列表。
Then, run merge on couples 然后,对夫妇运行合并
[merge(lst[i], lst[i+1] ) for i in range(0,len(lst),2) ]
This process should be repeated as long as the list has more than two elements, and if the number of elements is odd, append [] to it 只要列表包含两个以上的元素,就应该重复此过程,并且如果元素的数目为奇数,请在其后面附加[]
Method 1: 方法1:
import heapq
x = [[1, 2, 3], [3, 4, 5],[2, 3, 4], [4, 7, 8]]
y = list(heapq.merge(*x))
Method 2: 方法2:
import itertools
y = sorted(itertools.chain(*x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.