python - 有没有办法在 python 中使用这个标准修改列表?
问题描述
假设我们有一组有序的元素[a, b]
:
初始设置
[[1,5], [2,5], [3,5], [3,6], [4,5]]
由于我对4 个元素的集合感兴趣,并且我看到元素 2 和 3 具有相同的值a
,我想知道如何编写一个从初始集合开始并执行以下操作的程序:
设置 1
[[1,5], [2,5], [3,5], [4,5]]
设置 2
[[1,5], [2,5], [3,6], [4,5]]
例如,如果初始集合是:
[[1,5], [2,5], [3,5], [3,6], [4,5], [4,6]]
该程序应返回:
[[1,5], [2,5], [3,5], [4,5]]
[[1,5], [2,5], [3,5], [4,6]]
[[1,5], [2,5], [3,6], [4,5]]
[[1,5], [2,5], [3,6], [4,6]]
python有没有办法做到这一点?我曾尝试使用combinations
andpermutations
模块,但在我看来,这对于任务的简单性来说太过分了。
非常感谢。
解决方案
按第一个元素分组,然后得到product
:
import collections, itertools
lst = [[1,5], [2,5], [3,5], [3,6], [4,5]]
d = collections.defaultdict(list)
for x in lst:
d[x[0]].append(x)
res = list(itertools.product(*d.values()))
# [([1, 5], [2, 5], [3, 5], [4, 5]),
# ([1, 5], [2, 5], [3, 6], [4, 5])]
如果列表按第一个元素排序,您也可以groupby
按照其他答案所示使用,然后获取那些的`product:
from itertools import product, groupby
for x in product(*(list(g) for k, g in groupby(lst, key=lambda x: x[0]))):
print(x)
推荐阅读
- php - 根据 Woocommerce 中的购物车商品数量为产品价格添加额外费用
- c# - 升级到 DotNet Core 2.2 后 Azure 应用服务不运行
- sql - 仅返回特定文档 ID 的最近邮寄日期
- json - 在 JSON 文件中搜索一个有效的 IP 地址并抓取它
- elasticsearch - 如何使用 NEST 与 ElasticSearch 进行 guid 匹配
- apache-camel - 如何以动态方式将大小值传递给重新排序器?
- javascript - 在 Acrobat 10 Pro 中设置和访问文档级变量
- javascript - 在反应本机选项卡导航器的屏幕之间传递对象
- php - 如何让我的 cron 工作在 cpanel 中工作?
- javascript - 如何将位置列表加载到 Google 地图中,然后通过给定的城市/zip 搜索最近的位置?