相关疑难解决方法(0)

"对于带有基数10的int()的无效文字:"这实际上意味着什么?

初学者来了!我正在编写一个简单的代码来计算项目在列表中显示的次数(例如,count([1, 3, 1, 4, 1, 5], 1)将返回3).

这是我原来的:

def count(sequence, item):
    s = 0
    for i in sequence:
       if int(i) == int(item):
           s += 1
    return s
Run Code Online (Sandbox Code Playgroud)

每次我提交这段代码,我都会

"带有基数10的int()的无效文字:"

我已经发现正确的代码是:

def count(sequence, item):
    s = 0
    for i in sequence:
       if **i == item**:
           s += 1
    return s
Run Code Online (Sandbox Code Playgroud)

但是,我只是好奇这个错误陈述的含义.为什么我不能留下来int()

python int

4
推荐指数
1
解决办法
4万
查看次数

按因子选择数据框中的第n个元素

我有一个带有文本列name和因子的数据框city.它首先按字母顺序排序city然后name.现在我需要获得一个数据框,每个数据框中只包含第n个元素city,保持这种顺序.如何在没有循环的情况下以漂亮的方式完成?

我有:

name    city
John    Atlanta
Josh    Atlanta
Matt    Atlanta
Bob     Boston
Kate    Boston
Lily    Boston
Matt    Boston
Run Code Online (Sandbox Code Playgroud)

我想要一个函数,它返回第n个元素city,即如果它是第3个,那么:

name    city
Matt    Atlanta
Lily    Boston
Run Code Online (Sandbox Code Playgroud)

它应该返回NULL,name如果它超出了所选的范围city,即第4:

name    city
NULL    Atlanta
Matt    Boston
Run Code Online (Sandbox Code Playgroud)

请仅使用基础R?

r

2
推荐指数
1
解决办法
4252
查看次数

更有效的方法来获取data.table中的每个第n个元素

线程讨论了如何为数据框做这件事.我想做一点比这更复杂的事情:

dt <- data.table(A = c(rep("a", 3), rep("b", 4), rep("c", 5)) , B = rnorm(12, 5, 2))
dt2 <- dt[order(dt$A, dt$B)] # Sorting
# Always shows the factor from A
do.call(rbind, by(
  dt2, dt2$A,
  function(x) data.table(A = x[,A][1], B = x[,B][4])
              )
        )
#This is to reply to Vlo's comment below. If I do this, it will return both row as 'NA'
    do.call(rbind,
        by(dt2, dt2$A, function(x) x[4])
      )
# Take the max value of B according to each …
Run Code Online (Sandbox Code Playgroud)

r data.table

0
推荐指数
1
解决办法
605
查看次数

标签 统计

r ×2

data.table ×1

int ×1

python ×1