在Python中打印列表的最后三项

时间:2017-04-19 17:58:11

标签: python

public HttpResponseMessage GetAvailableHospitalsByAjax(System.Guid? DirectorateOfHealthID = null, System.Guid? UnitTypeID = null, string DeviceTypeIDs = null)
{
    Context db = new Context();
    var query = db.Hospitals.AsQueryable();
    if (UnitTypeID != null)
    {
        query = query.Where(j => j.HospitalDepartments.Any(www => www.Units.Any(u => u.UnitTypeID == UnitTypeID)));
    }

    if (DirectorateOfHealthID != null)
    {
        query = query.Where(h => h.DirectorateHealthID == DirectorateOfHealthID);
    }


    query = query.Where(j => j.HospitalDepartments.Any(u => u.Units.Any(d => d.Devices.Any(s => s.Status == Enums.DeviceStatus.Free)))
    && j.HospitalDepartments.Any(hd => hd.Units.Any(u => u.Beds.Any(b => b.Status == Enums.BedStatus.Free))));



    var list = query.ToList().Select(w => new HospitalInfo()
    {
        Id = w.ID,
        Name = w.Name 

    }).ToList();


    return Request.CreateResponse(HttpStatusCode.OK, list);
}

我明白了:

pizzas  = ["hawai","salame","vegetable","capriciosa","new york"]
for pizza in pizzas:
    print("I like " + pizza.title() + " pizza!")
print("\n" + "The first three pizzas in the list are: " + str(pizzas[0:3]))
print("\n" + "The last three pizzas in the list are: " + str(pizzas[-1:-3]))
我很困惑。 Isn' t I like Hawai pizza! I like Salame pizza! I like Vegetable pizza! I like Capriciosa pizza! I like New York pizza! The first three pizzas in the list are: ['hawai', 'salame', 'vegetable'] The last three pizzas in the list are: [] 表示列表中的最后一个元素?我正在为-1编制索引,所以不应该打印我最后3个项目吗?我究竟做错了什么 ?

2 个答案:

答案 0 :(得分:5)

您应该使用pizzas[-3:],这样您的start就是列表末尾的第三个元素,而end就是列表的最后一个。

pizzas  = ["hawai","salame","vegetable","capriciosa","new york"]

for pizza in pizzas:
    print("I like " + pizza.title() + " pizza!")

print("\nThe first three pizzas in the list are: " + str(pizzas[:3]))
print("\nThe last three pizzas in the list are: " + str(pizzas[-3:]))

答案 1 :(得分:3)

默认步长为1,因此从-1到-3,步长为1将返回一个空切片。您可以明确地将步骤指示为-1,但这会颠倒项目的顺序:

>>> pizzas[-1:-3:-1] 
['new york', 'capriciosa'] # -3 excluded

但是,要获得最后三项,您需要的是pizza[-3:]