2016-11-02 35 views
-2

只是一個預警:我剛剛開始編程,Python是我的第一語言,也是迄今爲止唯一的語言。Python:是否有一個內建工作與.index()相似但相反?

有沒有一種內部工作方式與.index()相反?我在尋找這個,因爲我做了一個bool函數,我有一個int列表,我想返回True,如果給定的int列表是[x^0, x^1, x^2, x^3, ...]形式的某個int x的冪的列表,否則返回'False'。

我想在代碼中說的線沿線的是:

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

編輯:對不起,我不知道如何格式化在這裏 OK生病說明我的意思:

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)並閱讀了描述。我問什麼,是不是可以作爲一個列表方法:(

遺憾的任何不便

+6

'list [4]''怎麼樣?我建議閱讀基礎知識,例如參見http://sopython.com/wiki/What_tutorial_should_I_read%3F – jonrsharpe

+0

我已經嘗試過了,但是我無法使其通用於申請所有項目。 – Marco

+0

雖然我會檢查鏈接,謝謝。 – Marco

回答

-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 
+0

這可能還有很多不僅僅是索引到列表中。 – Makoto

+1

但這個問題具體到:*是否有內建我可以用來輸入位置並返回列表中的項目?*否則是OP試圖實現 –

+0

lol更多吧? ......他在評論中說了些什麼,但是從他給我們的東西我可以說這是答案(雖然不是真的值得回答) –

-1
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開頭,如果它是有效的...

+0

我的文檔字符串是否使我的問題更清晰? – Marco

+0

不錯downvote ...關心分享? –

相關問題