如何通过输入(lst)位置的整数来告诉python使用lst中的特定值

如何通过输入(lst)位置的整数来告诉python使用lst中的特定值,python,python-3.x,Python,Python 3.x,我是一个新的编码,我花了一个多小时寻找这个没有运气 所以我有一个def函数,它接受一个lst和一个位置作为输入 我需要python将输入的位置对应到lst,并使用反映在lst位置上的任何值来进一步计算 def somefunction(lst, position): for i, value in enumerate(lst): if value < int(position): #this just uses the inputed

我是一个新的编码,我花了一个多小时寻找这个没有运气

所以我有一个def函数,它接受一个lst和一个位置作为输入

我需要python将输入的位置对应到lst,并使用反映在lst位置上的任何值来进一步计算

    def somefunction(lst, position):
        for i, value in enumerate(lst):
            if value < int(position):    #this just uses the inputed value position and not the actual position value from the list
                count += 1
        return count

    >>> somefunction([21, 4, 5, 66, 4, 3, 555], 2)
    2
def somefunction(lst,位置):
对于i,枚举中的值(lst):
如果值>>somefunction([21,4,5,66,4,3555],2)
2.
所以在位置2,我们有5,我需要我的代码返回一个小于5的所有数字的计数,只在它的右边。所以答案是2。。。。。。因为4和3小于5

在python中,位置
n
后面的列表的“尾部”是
lst[n+1::

>>> lst = [21, 4, 5, 66, 4, 3, 555]
>>> n = 2
>>> tail = lst[n+1:]
>>> tail
[66, 4, 3, 555]
要选择满足特定条件的所有元素,请使用“列表理解”:

希望这有帮助。

在python中,位置
n
后面的列表的“尾部”是
lst[n+1:][/code>:

>>> lst = [21, 4, 5, 66, 4, 3, 555]
>>> n = 2
>>> tail = lst[n+1:]
>>> tail
[66, 4, 3, 555]
def somefunction(my_list, index):
    value, tail = my_list[index], my_list[index + 1:]
    return sum(1 for element in tail if element < value)
要选择满足特定条件的所有元素,请使用“列表理解”:

希望这有帮助。

def somefunction(我的列表,索引):
def somefunction(my_list, index):
    value, tail = my_list[index], my_list[index + 1:]
    return sum(1 for element in tail if element < value)
值,tail=my_list[index],my_list[index+1:] 返回和(如果元素<值,则尾部元素为1)
def somefunction(我的列表,索引):
值,tail=my_list[index],my_list[index+1:]
返回和(如果元素<值,则尾部元素为1)
def somefunction(lst,位置):
计数=0
对于范围内的i(位置,len(lst)):
如果lst[i]
有很多方法可以做到这一点。正如上面的人所说。既然你问了一些与你的代码类似的问题,我希望这能帮助你。但作为初学者,您还可以探索所有选项

def somefunction(lst,position):
计数=0
对于范围内的i(位置,len(lst)):
如果lst[i]

有很多方法可以做到这一点。正如上面的人所说。既然你问了一些与你的代码类似的问题,我希望这能帮助你。但是作为初学者,你也可以探索所有选项

我不明白,所以你想传入一个索引,然后找到比列表中具有该索引的元素小的元素数?是的,索引将用作列表中的一个位置…无论哪个值在该位置…然后找到我不明白的元素数,因此,您希望传入一个索引,然后查找比列表中具有该索引的元素小的元素数?是的,索引将用作列表中的一个位置…无论哪个值位于该位置…然后查找元素数小这不起作用,因为当我们使用某个函数时([1,4,2,9,4],2)答案应该是2,但它显示0@Michelle:9和4怎么比2小?@Michelle现在我真的很困惑。很抱歉我看错了东西。现在试着去理解它就行了。我的代码的一些变体可以用来获得相同的结果吗?这不起作用,因为当我们使用一些函数([1,4,2,9,4],2)时,答案应该是2,但它显示了0@Michelle:9和4怎么比2小?@Michelle现在我真的很困惑。很抱歉我看错了东西。现在就试着去理解它,这很好。我的代码的一些变体可以用来得到同样的结果吗?
def somefunction(lst, position):
   count=0
   for i in range(position,len(lst)):
       if lst[i] < lst[position]:    
          count += 1
   return count


somefunction([21, 4, 5, 66, 4, 3,555], 2)