首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将长度较短的列表平均分配到另一个列表?

如何将长度较短的列表平均分配到另一个列表?
EN

Stack Overflow用户
提问于 2020-11-26 18:22:03
回答 1查看 61关注 0票数 1

我有两份名单。第一个名为location,长度可以从1到无穷大不等。

代码语言:javascript
复制
location = ['loc1,'loc2','loc3','loc4,'loc5','loc6','loc7,'loc8','loc9','loc10,'loc11','loc12','loc13,'loc14','loc15','loc16,'loc17','loc18','loc19,'loc20','loc21','loc22,'loc23','loc24','loc25','loc26','loc27',] <- Please note that length could from 1 to infinite number

第二个列表名为审计师。它的长度通常大于位置列表长度。如果不是第一位或最后一位审核员,我想要将所有审计师平均分配到其他地点。

代码语言:javascript
复制
auditor = ['aone','atwo','athree','afour','afive','asix','aseven','aeight','anine','aten','aeleven','atwelve','athirteen','afourteen','afitheen','asixteen,'aseventeen''] <- Please note that length could from 1 to infinite number

下面的代码对大多数情况都很有用,但是当位置为28,审计师为17时,代码就失败了。

代码语言:javascript
复制
df2['location'] = location
df2['auditor'] = [auditor[int(df2)] for df2 in np.arange(0, len(auditor), (len(auditor)/len(df2)))]

我想要的输出是获得尽可能多的甚至被划分的列表,并且它必须在每一种情况下工作,只要位置大于审计师。

My_desired_output = 'aone','aone‘'atwo','atwo','aten','afour',’a5‘,’a5‘,'asix','aseven','aseven',’a8‘,'anine','aten',’a11‘,’a11‘,'atwelve',’a13‘,’a13‘,'afour',‘A15’,‘16’,‘17’]

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-26 18:32:43

您可以考虑使用在chunked中找到的more-itertool函数

代码语言:javascript
复制
from more_itertools import chunked
from math import ceil
from typing import List, Any, Tuple, Iterator


def distribute_evenly(items: List[Any], cells: List[Any]) -> Iterator[Tuple[Any, List[Any]]]:
    if len(items) <= len(cells):
        item_chunks = [[item] for item in items] + [[]] * (len(cells) - len(items))
    else:
        chunk_size = int(ceil(len(items) / len(cells)))
        item_chunks = chunked(auditor, chunk_size)
    
    return zip(cells, item_chunks)


location = ["loc1", "loc2", "loc3"]
auditor = ["aud1", "aud2", "aud3", "aud4", "aud5", "aud6", "aud7", "aud8"]


auditor_per_location = list(distribute_evenly(auditor, location))

# auditor_per_location is now [('loc1', ['aud1', 'aud2', 'aud3']), ('loc2', ['aud4', 'aud5', 'aud6']), ('loc3', ['aud7', 'aud8'])]

祝好运!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65027440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档