You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用等长的list2重排list1并保持两者的列表格式?

基于list2对list1重排序并保持列表格式

可以通过以下步骤实现,核心是从list2中提取排序索引,再用该索引重新排列两个列表:

  1. 定义原始列表:
list1 <- list("two", "one", "three")
list2 <- list(2, 1, 3)
  1. 生成排序索引:将list2转换为向量后,用order()函数获取按值排序后的位置索引
sort_idx <- order(unlist(list2))
  1. 用索引对两个列表重排序,结果仍保持列表格式:
list1 <- list1[sort_idx]
list2 <- list2[sort_idx]

验证输出:

> list1
#[[1]]
#[1] "one"
#
#[[2]]
#[1] "two"
#
#[[3]]
#[1] "three"

> list2
#[[1]]
#[1] 1
#
#[[2]]
#[1] 2
#
#[[3]]
#[1] 3

说明

unlist(list2)将列表转换为普通向量c(2,1,3),order()函数返回该向量按升序排列后的元素位置c(2,1,3),用这个位置索引去取原列表的元素,就能得到按list2值排序后的结果,且排序后的对象依然是列表类型。

内容的提问来源于stack exchange,提问作者ZT_Geo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 13:05:29