按字符串值分组生成对应数组:for循环取值归类的实现是否可行?
当然可以实现!
这个需求完全没问题,核心逻辑其实很简单:先提前准备好对应类别的目标数组,然后每次从源数组取出字符串后,把它追加到对应的数组里就行——不管循环多少次,所有"1st"都会往同一个数组里塞,绝不会新建额外的数组。
我用Python写个示例代码给你看看,不管是循环6次(刚好遍历一遍源数组)还是20次,逻辑都能正常工作:
# 先初始化我们要的三个目标数组 first_group = [] second_group = [] third_group = [] # 你提供的源数组 source_list = ("1st", "2nd", "1st", "3rd", "3rd", "1st") # 循环20次,每次按顺序从源数组取元素(用取模实现循环遍历源数组) for idx in range(20): current_item = source_list[idx % len(source_list)] # 根据元素值分类追加 if current_item == "1st": first_group.append(current_item) elif current_item == "2nd": second_group.append(current_item) elif current_item == "3rd": third_group.append(current_item) # 打印结果 print("第一个数组:", first_group) print("第二个数组:", second_group) print("第三个数组:", third_group)
如果是只循环6次(刚好走一遍源数组),结果就和你举的例子完全一致:第一个数组是["1st", "1st", "1st"],第二个是["2nd"],第三个是["3rd", "3rd"]。要是循环20次,每个数组里的元素数量会按源数组的比例增加,但分类规则始终生效——所有"1st"都会进第一个数组,不会出现其他意外。
要是以后可能新增更多类别,用字典来管理会更灵活,不用逐个初始化数组:
source_list = ("1st", "2nd", "1st", "3rd", "3rd", "1st") # 用字典映射类别和对应的数组 category_groups = {"1st": [], "2nd": [], "3rd": []} for idx in range(20): current_item = source_list[idx % len(source_list)] category_groups[current_item].append(current_item) # 再提取成你需要的单独数组 first_group = category_groups["1st"] second_group = category_groups["2nd"] third_group = category_groups["3rd"]
总之这个需求逻辑非常清晰,完全可以实现,核心就是根据元素的标识,把它持续追加到对应的固定容器里。
内容的提问来源于stack exchange,提问作者NeonSmash
相关产品推荐
相关产品推荐

