【问题标题】:hello, how do I modify to get the next node in the list only?您好,如何修改以仅获取列表中的下一个节点?
【发布时间】:2021-11-09 03:40:01
【问题描述】:

假设 list = [5,9,2,4,3] 并且我输入 Node = 9,只会输出 2。下面是代码,但目前,它输出所有下一个元素。

pos = list1.index(3) # list1 = [5,9,2,4,3]
i = pos+1
listLen = len(list1)
while i < listLen:
  print(list1[i])
  i+=1

【问题讨论】:

标签: python python-2.7


【解决方案1】:

你可以用 slice 来做

list1 = [5, 9, 2, 4, 3]
try:
    pos = list1.index(9)
    print(*list1[pos + 1:pos + 2]) # get the slice and unpack (with *) the value
except ValueError:  # it is also advisable to handle the option of the absence of an element in the list
    print('No such item in the list')

打印:

2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2012-10-14
    • 1970-01-01
    • 2015-11-10
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多