[英]How to divide python list into sublists of unequal length?
我試圖將逗號分隔的元素列表分成不等長的塊。 我該如何划分?
list1 = [1, 2, 1]
list2 = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]
list1 包含我希望將 list2 划分為塊大小的元素。
您可以結合itertools.accumulate
和列表itertools.accumulate
的強大功能:
In [4]: from itertools import accumulate
In [5]: data = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]
In [6]: lengths = [1, 2, 1]
In [7]: [data[end - length:end] for length, end in zip(lengths, accumulate(lengths))]
Out[7]: [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
itertools.accumulate
返回一個迭代器到累積和的序列。 通過這種方式,您可以輕松計算源數組中每個塊的結尾:
In [8]: list(accumulate(lengths))
Out[8]: [1, 3, 4]
另一個解決方案
list1 = [1,2,1]
list2 = ["1.1.1.1","1.1.1.2","1.1.1.3","1.1.1.4"]
chunks = []
count = 0
for size in list1:
chunks.append([list2[i+count] for i in range(size)])
count += size
print(chunks)
# [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
您也可以為此使用itertools.islice
。 它高效且易於閱讀:
def unequal_divide(iterable, chunks):
it = iter(iterable)
return [list(islice(it, c)) for c in chunks]
然后使用它:
>>> list1 = [1, 2, 1]
>>> list2 = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]
>>> unequal_divide(list1, list2)
[['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
或者作為生成器:
def unequal_divide(iterable, chunks):
it = iter(iterable)
for c in chunks:
yield list(islice(it, c))
使用中:
>>> list(unequal_divide(list1, list2))
[['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
這也在more-itertools.split_at
。 請參閱此處獲取他們的源代碼,該代碼幾乎相同,但不允許提供任何塊,這很奇怪。
你也可以像這樣使用.pop()
方法:
list1 = [1, 2, 1]
list2 = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]
new_list = []
for chunk in list1:
new_list.append( [ list2.pop(0) for _ in range(chunk)] )
print(new_list)
# [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
這將修改原始list2 。
類似的東西:
def divideUnequal(list1, list2):
counter=0
step=0
divided=[]
for count in list1:
step= counter+ count
sublist= list2[counter: step]
counter= step
divided.append(sublist)
return divided
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.