【问题标题】:Sorting Nested Lists in R with Python Semantics使用 Python 语义对 R 中的嵌套列表进行排序
【发布时间】:2022-01-14 16:23:50
【问题描述】:

我需要在 R 中复制以下排序行为(在 Python 中找到)。

假设在 Python 中:

l = [(0,0), (1,-1), (-1,0), (-1,-1)]

>>> sorted(l)
[(-1, -1), (-1, 0), (0, 0), (1, -1)]

>>> min(l)
[(-1, -1)]

R中等价的数据结构是:

l <- list(c(0,0), c(1,-1), c(-1,0), c(-1,-1))

sort() 和 sort.list() 方法不适用于非原子向量。

在我的用例中,我可以保证长度为 2 的向量列表,所以这可行:

sorted <- function(list){
  m=matrix(unlist(list), ncol = 2, byrow = T)
  asplit(
    m[order(m[,1],m[,2]),],
    1
  )
}

从 Python 中复制 min 的行为很容易,只依赖于 R 中 sorted 实现的正确功能。

min.list &lt;- function(list) sorted(list)[1]

非常感谢有关实现与 sorted 相同行为的建议,特别欢迎考虑效率。

对我的实现来说是不必要的,但另一个考虑因素是子列表长度不同时的 sorted 行为。

>>> sorted([(0,0), (1,1), (0,-1), (0,-1, 0), (0,-1,-1), (0, 0, 0)])

[(0, -1), (0, -1, -1), (0, -1, 0), (0, 0), (0, 0, 0), (1, 1)]

提前致谢

【问题讨论】:

  • 问题本身没有排序。相反,python 为这样的序列实现排序,特别是字典顺序。

标签: python r sorting


【解决方案1】:

一种选择是将行绑定到矩阵,按列拆分并使用order() 获取索引。对于参差不齐的数据,首先需要对长度进行标准化,但如果保证数据长度相等,显然可以跳过这一步以稍微提高效率。

l <- list(c(0, 0), c(1, 1), c(0, -1), c(0, -1, 0), c(0, -1, -1), c(0, 0, 0))

l[do.call(order, c(asplit(do.call(rbind, lapply(l,
    `length<-`, max(lengths(l)))), 2), na.last = FALSE))]

[[1]]
[1]  0 -1

[[2]]
[1]  0 -1 -1

[[3]]
[1]  0 -1  0

[[4]]
[1] 0 0

[[5]]
[1] 0 0 0

[[6]]
[1] 1 1

【讨论】:

    【解决方案2】:

    也许我们可以试试这个方法

    > l <- list(c(0, 0), c(1, 1), c(0, -1), c(0, -1, 0), c(0, -1, -1), c(0, 0, 0))
    
    > l[order(sapply(l, toString))]
    [[1]]
    [1]  0 -1
    
    [[2]]
    [1]  0 -1 -1
    
    [[3]]
    [1]  0 -1  0
    
    [[4]]
    [1] 0 0
    
    [[5]]
    [1] 0 0 0
    
    [[6]]
    [1] 1 1
    

    【讨论】:

    • 原则上,将数字输入转换为字符串进行排序是不安全的,因为这可能会引入排序规则问题。
    猜你喜欢
    • 1970-01-01
    • 2010-09-21
    • 2014-08-03
    • 2013-01-21
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多