【问题标题】:Python: Is There a builtin that works similar but opposite to .index()?Python:是否有一个与 .index() 类似但相反的内置函数?
【发布时间】:2023-03-07 18:19:01
【问题描述】:

只是一个警告:我最近才开始编程,Python 是我的第一语言,也是迄今为止唯一的语言。

是否有与.index() 以相反方式工作的内置函数?我正在寻找这个,因为我创建了一个 bool 函数,其中有一个整数列表,如果给定的整数列表是 [x^0, x^1, x^2, x^3, ...] 和 `否则为假。

我想在代码中说的是:

n >= 1  
while the position(n+1) = position(1)*position(n) 
    for the length of the list
    return True
otherwise 
    False.

是否有一个内置函数可以用来输入位置并返回列表中的项目?

list = [1,2,4,8,16]
position(4)

返回整数 16。

编辑:抱歉,我不知道如何格式化 好的,我的意思是:

def powers(base):
''' (list of str) -> bool
Return True if the given list of ints is a list of powers of 
some int x of the form [x^0, x^1, x^2, x^3, ...] and False 
otherwise.
>>> powers([1, 2, 4, 8]) 
True
>>> powers([1, 5, 25, 75])
False
'''

最终编辑:

我刚刚从这里 (https://docs.python.org/2/tutorial/datastructures.html) 浏览了所有可用的列表方法并阅读了描述。我要的东西不能作为列表方法使用:(

抱歉给您带来不便。

【问题讨论】:

标签: python built-in


【解决方案1】:

作为回答:

是否有一个内置函数可以用来输入位置并返回列表中的项目?

您只需要访问list,其索引为:

>>> my_list = [1,2,4,8,16]
>>> my_list[4]
16  # returns element at 4th index

而且,此属性与语言无关。所有语言都支持这一点。


根据您对问题的编辑,您可以将函数编写为:

def check_value(my_list):
    # if len is less than 2
    if len(my_list) < 2:
        if my_list and my_list[0] == 1:
            return True
        else:
            return False 
    base_val = my_list[1] # as per the logic, it should be original number i.e num**1 
    for p, item in enumerate(my_list):
        if item != base_val ** p: 
            return False
    else:
        return True

示例运行:

>>> check_value([1, 2, 4, 8])
True
>>> check_value([1, 2, 4, 9])
False
>>> check_value([1, 5, 25, 75])
False

【讨论】:

  • 这可能不仅仅是索引到列表中。
  • 但问题是特定于:是否有一个内置函数可以用来输入位置并返回列表中的项目? OP 想要实现的其他目标
  • 大声笑更多吧? ...他在评论中说了一些类似的话,但从他给我们的内容来看,我会说这就是答案(虽然不值得回答)
  • check_value([1])
  • @JoranBeasley 处理了边缘场景。
【解决方案2】:
def powers(n):
    for i in itertools.count(0):
        yield n**i


def is_powers(li):
   if li[0] == 1:
      if len(li) > 1:
          return all(x==y for x,y in zip(li,powers(li[1])))
      return True
   return False

is_powers([1, 2, 4, 8])
is_powers([1, 5, 25, 75])

也许......它真的不清楚你在问什么......这假设它总是必须以 1 开头,如果它是有效的......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-11
    • 2016-10-15
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多