如何在python中进行反向切片?

时间:2017-05-11 02:29:25

标签: python slice

说我有user_ids = list(set(df["user_id"])) cates = list(set(df["cate"])) user_probs = pd.DataFrame() for uid in user_ids: d = pd.DataFrame({'user_id': [uid]}) for c in cates: ratio = df[(df["user_id"] == uid) & (df["cate"] == c)]["prob"] ratio = 0 if len(ratio)==0 else float(ratio) d["cate_"+c+"_prob"] = ratio user_probs = pd.concat([user_probs, d]) ,我想以相反的顺序访问最后两个元素,如lst = [1, 2, 3]

如何使用切片来做到这一点?

3 个答案:

答案 0 :(得分:5)

简单地将边界放入切片中:

Project is running at http://localhost:9000/
webpack output is served from /
Content not from webpack is served from /Users/dd/Desktop/apps/webpack-starter/dist

在切片>>> [1,2,3][-1:-3:-1] [3, 2] 中:

  • 第一个元素是我们想要开始的位置(-1:-3:-1);
  • 第二个是我们希望停止的地方(不包括在内);
  • ,第三个是方向(或跳过)(向后)。

答案 1 :(得分:1)

  • [ - 2 ::]将返回最后两个元素
  • [:: - 1]会反转它

所以答案是:

lst[-2::][::-1]

我检查了@ donkopotamus的回答,这实际上是最好的答案

答案 2 :(得分:1)

获取最后两个元素!

然后反过来!

>>> lst
[1, 2, 3]
>>> lst[-2:][::-1]
[3, 2]