Python:是否有一个与.index()类似但相反的内置函数? [英] Python: Is There a builtin that works similar but opposite to .index()?

查看:191
本文介绍了Python:是否有一个与.index()类似但相反的内置函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是一个警告:我最近才开始编程,而Python是到目前为止我的第一门语言,也是唯一的语言。

Just a forewarning: I just recently started programming and Python is my first language and only language so far.

是否有一个内置的内建函数与 .index()?我正在寻找它是因为我做了一个布尔函数,其中有一个整数列表,并且如果给定的整数列表是幂的列表,我想返回 True 某些形式为 [x ^ 0,x ^ 1,x ^ 2,x ^ 3,...] 的int,否则为False。

Is there a builtin that works in the opposite way of .index()? I'm looking for this because I made a bool function where I have a list of ints and I want to 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.

我想在代码中说的是:

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

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

Is there a builtin I could use to input the position and return the item in the list?

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

返回整数16。

编辑:抱歉,我不知道如何在这里格式化
好​​,请显示我的意思:

sorry I don't know how to format on here ok ill show what I mean:

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 ),然后阅读说明。我要的东西不能作为列表方法使用:(

I just went through all of the available list methods from here (https://docs.python.org/2/tutorial/datastructures.html) and read the descriptions. What I'm asking for, isn't available as a list method :(

抱歉给您带来的不便。

推荐答案

作为对以下内容的解答:

As an answer to:


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

Is there a builtin I could use to input the position and return the item in the list?

您只需要访问列表其索引为:

You just need to access the list with it's index as:

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

而且,此属性与语言无关,所有语言均支持。

And, this property is independent of language. All the languages supports this.

根据您在问题,您可以将函数编写为:

Based on your edit in the question, you may write your function as:

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

这篇关于Python:是否有一个与.index()类似但相反的内置函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆