【问题标题】:Getting the nth values from a list to run through a list without a for-loop从列表中获取第 n 个值以在没有 for 循环的情况下运行列表
【发布时间】:2021-04-03 12:42:32
【问题描述】:

list_ 包含许多整数,我想得到它的第 n 个值。第 n 个值包含在 list_ 变量中。所以我想打印list_[10], list_[25], list_[45]....。有没有一种方法可以在不使用for-loop 的情况下做到这一点,使用列表中的范围函数可能是list_[:]

list_ = [ 5268, 6760,  6761 ... 15149, 15150, 15151]
list_2= [10,25,45,60,90]

【问题讨论】:

  • 我们可以对这个任务使用递归和切片,它不需要for循环。

标签: python-3.x list dataset range


【解决方案1】:

在这种情况下使用的最佳方法是recursion 在切片的帮助下。任何iteration 任务都可以使用recursion 执行,并且由于性能缺点对于这个特定问题来说是微不足道的,所以使用recursion 是有意义的。

假设我们有两个列表 list_1list_2

def rec_increment(list_2,list_1):
    if len(list_2) == 0:
        return ""                                 #so that it doesn't print 'none' in the end   
    else:
        print(list_1[list_2[0]])                
        return rec_increment(list_2[1:],list_1)   #only recur on the 2nd-nth part of the list
list_1= [0,10,20,30,40,50,60,70,80,90,100]
list_2= [1,2,4,5]
rec_increment(list_2,list_1)                  #gives 10 20 40 50

如果条件只是不使用for-loop,你也可以在java中使用forEach(),甚至是while循环。

【讨论】:

  • 如果解决了您的问题,请考虑接受该解决方案。
【解决方案2】:

我认为你不能只使用range 函数。

最简单的方法是这个:

result = [list_[i] for i in list_2]
print(result)

但这里有一些其他方式:https://blog.finxter.com/python-list-arbitrary-indices/

【讨论】:

  • 这仍然使用 for 循环。这如何回答这个问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多