如何使用del和index从列表中删除元素

时间:2020-01-14 16:21:41

标签: python list del

我有一个列表,所有2都需要删除:

MarkLabel

我也有L的所有2的索引:

L = [1, 2, 3, 2, 4, 8, 2]

如何使用myIndex = [1, 3, 6] 从L中删除所有2?

我尝试过del,但没有用。

3 个答案:

答案 0 :(得分:2)

您可以在for循环中使用del,以确保索引以相反的顺序排序:

for i in sorted(myIndex, reverse=True):
    del L[i]

print(L)
[1, 3, 4, 8]

答案 1 :(得分:1)

这是因为每次发生删除并且列表变短时,索引都会偏离1。更加Python化的方法是将仍然有效的所有内容收集到新列表中。这可以通过简单的列表理解来完成,如下所示:

L2 = [i for i in L if i != 2]

>>> L2
[1, 3, 4, 8]

或者,您可以使用filter

L3 = list(filter(lambda x: x != 2, L))

>>> L3
[1, 3, 4, 8]

答案 2 :(得分:0)

您可以使用remove函数删除所有2个元素。

library(tidyverse)

# example data
tbl_1 <- data.frame(DocDate = as.Date(c("2017-01-03", "2017-02-07", "2017-03-04")),
                    State1 = c("RI", "CT", "GA"),
                    MD = c(78, 115, 127),
                    OD = c(150, 220, 235))

tbl_2 <- data.frame(begin = as.Date(c("2017-01-01", "2017-01-29", "2017-02-26")),
                    Period_Ending = as.Date(c("2017-01-29", "2017-02-26", "2017-03-26")))


tbl_2 %>%
  mutate(date = map2(begin, Period_Ending , ~seq(.x, .y, "day"))) %>%  # create a sequence of dates (begin to end)
  unnest(date) %>%                                                     # save it as column
  inner_join(tbl_1, by=c("date" = "DocDate")) %>%                      # join the other dataset
  select(DocDate = date, State1, MD, OD, Period_Ending)                # re-ararnge columns


# # A tibble: 3 x 5
#   DocDate    State1    MD    OD Period_Ending
#   <date>     <fct>  <dbl> <dbl> <date>       
# 1 2017-01-03 RI        78   150 2017-01-29   
# 2 2017-02-07 CT       115   220 2017-02-26   
# 3 2017-03-04 GA       127   235 2017-03-26