【问题标题】:Python, remove all elements in a list of index > nPython,删除索引列表中的所有元素> n
【发布时间】:2017-02-10 18:08:09
【问题描述】:

假设我有一个清单:

myList = [1,2,3,4,5,6,7,8]

现在,假设我有一个用户输入了他们想要删除列表的索引。如何删除列表中索引大于输入值的所有元素,或重新创建具有新边界的列表?

例如)

x = input('Please enter index of last value in new list')
# say inputted value for x is 3
# I want to end the list at index 3 (i.e the new list will be [1,2,3,4])

实现我的目标最快的方法是什么?

【问题讨论】:

  • 您尝试过什么吗?...请分享您的尝试
  • myList[:] = myList[:int(x)]
  • “我将如何使用与 list.remove() python 函数配对的列表理解” - 将这些东西配对本质上总是一个糟糕的主意,而且这些工具都对您的任务没有用处。跨度>

标签: python indexing


【解决方案1】:
myList = [1,2,3,4,5,6,7,8]
x = input('Please enter index of last value in new list')
myList = myList[0:x+1]
print myList

【讨论】:

  • 看来OP需要从原始列表中删除一些元素,而不是创建一个新的。
  • 如果要修改原始列表:myList[:] = myList[0:x+1]
  • @PeterWood:或者del myList[x+1:],这可能更快。
  • @user2357112 我试过计时,你是对的。它似乎是恒定的时间,而且速度更快。
  • @PeterWood:这不是恒定时间,但它的主要优点是只需要查看索引 x+1 及以上而不是整个列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-02
  • 2017-12-16
  • 2020-01-02
相关资源
最近更新 更多