gpt4 book ai didi

python - 为每个重复元素创建具有给定索引的 Python 列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:14 25 4
gpt4 key购买 nike

第一个列表:包含对应类别名称的列表索引

第二个列表:包含作为字符串的类别名称

Intervals=[[Indexes_Cat1],[Indexes_Cat2],[Indexes_Cat3], ...]

Category_Names=["cat1","cat2","cat3",...]

期望的输出:

list=["cat1", "cat1","cat2","cat3","cat3"]

使用间隔列表放置输出列表中任何元素的索引。

Ex1:

Intervals=[[0,4], [2,3] , [1,5]]
Category_Names=["a","b","c"]

例如:输出 1

["a","c","b","b","a","c"]

编辑:更多运行案例

Ex2:

Intervals=[[0,1], [2,3] , [4,5]]
Category_Names=["a","b","c"]

例如:输出 2

["a","a","b","b","c","c"]

例 3:

Intervals=[[3,4], [1,5] , [0,2]]
Category_Names=["a","b","c"]

例如:Output3

["c","b","c","a","a","b"]

我的解决方案:

创建任何大小为 n 的空数组。

为每个类别运行一个 for 循环。

output=[""]*n
for i in range(len(Category_Names)):
for index in Intervals[I]:
output[index]=Categories[i]

是否有更好的解决方案,或者更 pythonic 的方式?谢谢

最佳答案

def categorise(Intervals=[[0,4], [2,3] , [1,5]],
Category_Names=["a","b","c"]):
flattened = sum(Intervals, [])
answer = [None] * (max(flattened) + 1)
for indices, name in zip(Intervals, Category_Names):
for i in indices:
answer[i] = name
return answer

assert categorise() == ['a', 'c', 'b', 'b', 'a', 'c']
assert categorise([[3,4], [1,5] , [0,2]],
["a","b","c"]) == ['c', 'b', 'c', 'a', 'a', 'b']

请注意,在此代码中,如果“间隔”未涵盖从零到最大间隔数的所有整数,您将在答案中得到 None 值。假定输入是兼容的。

关于python - 为每个重复元素创建具有给定索引的 Python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55087099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com