[英]Truncate sublists to the lowest length
我有:
l = [[1,2,3],[3,4],[1,6,8,3]]
我想:
[[1,2],[3,4],[1,6]]
哪個是列表l
,其中所有子列表都被截斷為在l
中找到的子列表的最低長度。
我試過了:
min = 1000
for x in l:
if len(x) < min: min = len(x)
r = []
for x in l:
s = []
for i in range(min):
s.append(x[i])
r.append(s.copy())
哪個有效,但寫起來很慢而且很長。 我想通過列表理解或類似方法來提高效率。
您可以找到列表中每個項目的長度,然后從中選擇最小元素。 稍后您可以使用此值截斷列表中的所有項目
l = [[1,2,3],[3,4],[1,6,8,3]]
min_length = min(map(len,l)) # using map with len function to get the length of each item and then using min to find the min value.
l = [item[:min_length] for item in l] # list comprehension to truncate the list
一個班輪 -
l = [item[:min(map(len,l))] for item in l]
關於zip
的一件有趣的事情是zip
本身就是相反的,所以list(zip(*zip(*x)))
給出了類似結構的x
。
並且zip
在任何輸入耗盡時停止迭代。
雖然結果是tuple
並且嵌套列表沒有被原地截斷,但可以利用它來構建以下 output:
Output:
[(1, 2), (3, 4), (1, 6)]
l = [[1, 2, 3], [3, 4], [1, 6, 8, 3]]
print(list(zip(*zip(*l))))
使用del
:
n = min(map(len, l))
for a in l:
del a[n:]
使用列表理解,單行:
l = [[1,2,3],[3,4],[1,6,8,3]]
print ([[s[i] for i in range(min([len(x) for x in l]))] for s in l])
或者:
print ([s[:min([len(s) for s in l])] for s in l])
Output:
[[1, 2], [3, 4], [1, 6]]
我們計算“range()”中子列表的最小長度,以迭代該數量的子列表並重建一個新的子列表。 頂級列表理解允許重構嵌套的子列表。
如果你有一個大的嵌套列表,你應該使用這個版本的兩行:
m = min([len(x) for x in l])
print ([[s[i] for i in range(m)] for s in l])
或者:
print ([s[:m] for s in l])
使用 zip 並保留列表對象:
print (list([list(x) for x in zip(*zip(*l))]))
Output:
[[1, 2], [3, 4], [1, 6]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.