python - 根据条件在列表中形成组
问题描述
(根据反馈编辑)
我有一个这样的列表:
my_list = [1,2,3,1,2,4,1,3,5,1,4,6,1,4,7]
我正在努力变成这样:
result = [[1,2,3,1,2,4],[1,3,5],[1,4,6,1,4,7]]
我想将 my_list 元素分组到 3 个元素的子列表中,除非 my_list[i] = my_list[i+3] 在这种情况下我想将它们合并到更大的子列表中。
这是我尝试过的:
result = []
for i in range(1,len(my_list),3):
try:
print(my_list[i],my_list[i+3])
if my_list[i] == my_list[i+3]:
result.extend(my_list[i-1:i+5])
else:
result.append(my_list[i-1:i+2])
解决方案
FWIW,您的逻辑描述不太清楚。但是,如果我正确理解您的代码,我认为这至少是正确的方向:
def stepper(my_list, step, bigger_step):
res = []
idx = 0
while idx <= len(my_list)-1:
if idx + step > len(my_list)-1:
# Remove this append if you don't want the "leftovers"
res.append(my_list[idx:])
break
if my_list[idx] != my_list[idx+step]:
res.append(my_list[idx:idx+step])
idx += step
else:
res.append(my_list[idx:idx+bigger_step])
idx += bigger_step
return res
my_list = [1,2,3,1,2,4,1,3,5,1,3,6,1,2,7]
print(stepper(my_list, step=3, bigger_step=6)) # Output: [[1, 2, 3, 1, 2, 4], [1, 3, 5, 1, 3, 6], [1, 2, 7]]
请注意,上述输出与您给定的示例不同,因为您提供的给定逻辑使第二个子列表和第一个子列表一样扩展。
使用上面的代码,如果我们bigger_step
使用 for 循环轻松更改,我们可以检查结果:
for big in range(4, 10):
print(f"Step: 3, Bigger_Step: {big}, Result:{stepper(my_list, step=3, bigger_step=big)}")
输出:
Step: 3, Bigger_Step: 4, Result:[[1, 2, 3, 1], [2, 4, 1], [3, 5, 1, 3], [6, 1, 2], [7]]
Step: 3, Bigger_Step: 5, Result:[[1, 2, 3, 1, 2], [4, 1, 3], [5, 1, 3], [6, 1, 2], [7]]
Step: 3, Bigger_Step: 6, Result:[[1, 2, 3, 1, 2, 4], [1, 3, 5, 1, 3, 6], [1, 2, 7]]
Step: 3, Bigger_Step: 7, Result:[[1, 2, 3, 1, 2, 4, 1], [3, 5, 1, 3, 6, 1, 2], [7]]
Step: 3, Bigger_Step: 8, Result:[[1, 2, 3, 1, 2, 4, 1, 3], [5, 1, 3], [6, 1, 2], [7]]
Step: 3, Bigger_Step: 9, Result:[[1, 2, 3, 1, 2, 4, 1, 3, 5], [1, 3, 6, 1, 2, 7]]
推荐阅读
- java - Spring Boot 未验证实体上的嵌入式对象
- angular - 如何在 angular apollo 客户端中停止轮询?
- asp.net - 将多个 301 重定向合并为一个用于 ASP.NET URL 重写模块
- typescript - VSCode Typescript Intellisense 在最简单的项目设置中不起作用
- javascript - CKEDITOR 使用 DecoupledEditor 看不到内容区域
- c++ - clang++ 编译时输出信息错误
- python - 如何让正则表达式在 B 的最大匹配次数后停止搜索 A
- apache-camel - 如何为周一至周五的日常会话配置 QuickFix/J?
- jquery - Jquery 表单提交在 IE11 上不起作用?
- sox - 使用 sox 更改音频通道数