2017-11-17 291 views
0

我相信我在我的代碼中出現了一個錯誤,我的列表元組垂直打印出來而不是正確的方式。可能有人請告訴我發生了什麼事?爲什麼我的元組列表是垂直的?

這是要問的問題: 枚舉它! 編寫一個名爲enum的函數,該函數接受一個序列並返回一個2元組列表,每個元組保存索引及其相關項目。

這是給定的例子:

>>> enum([45,67,23,34,88,12,90]) 
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)] 

>> enum('hello') 
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')] 

這是我的代碼:

def enum(aSequence): 
    for i in range(7): 
     b=aSequence[i] 
     a= [i] 
     list1 = [a,b] 
     print (list1) 


If following the example input is used this is the result: 
[[0], 45] 
[[1], 67] 
[[2], 23] 
[[3], 34] 
[[4], 88] 
[[5], 12] 
[[6], 90] 

我將期望的結果是: [(0,45),(1,67), (2,23),(3,34),(4,88),(5,12),(6,90)]

當我拿走print(list1)並使用return list1代替時,這是結果。

[[0], 13] 

爲什麼會出現這種情況?

當我把這個放到我正在接受輔導的網站上時,會顯示「傑克和簡」這個詞,如果是不同的測試,會顯示隨機數字。我的第二個問題是如何根據參數輸入獲取距離迴路。我試圖導入數學和隨機導入。雖然兩者都是短期解決方案,但它們不是長期解決方案。

我覺得我正在解決問題,因爲代碼在那裏只是基本的基礎知識可能會丟失。

回答

1

這是你需要在同一行

for i in range(len(aSequence)): 
    b=aSequence[i] 
    a= i 
    list1 = [a,b] 
    print (list1,end=' ') 

既然你想要的結果

打印一切什麼

[(0,45),(1,67),(2, (3,34),(4,88),(5,12),(6,90)]

+0

這將python3只工作(除非打印功能從__future__進口),而他並沒有指定版本。 – Nf4r

+0

@ Nf4r,哦好吧我認爲它是python3 –

1

你幾乎是正確的。問題出在你的a=[i]。通過使用[]括號來創建一個列表,所以a是一個列表,而不是一個int。 更改a=i它會沒事的。硬編碼range(7)應更改爲range(len(aSequence))。你理想的解決辦法是這樣的:

def enum(aSequence): 
    result = [] 
    for i in range(len(aSequence)): 
     result.append((i, aSequence[i])) 
    return result 

你需要記住的是一個事實,即print不是return

1

這是應該的。您需要在開始loop.Just像下面

def enum(aSequence): 
    list1 = [] 
    for i in range(len(aSequence)): 
     b = aSequence[i] 
     a = i 
     list1.append((a,b)) 
    print list1 

enum([45,67,23,34,88,12,90]) 
1

問題要求你回報與所需的結構列表之前創建的列表,所以要小心這一點。你現在正在打印一張。

def enum(aSequence): 
    list1 = [] 
    for i in range(len(aSequence)): 
     b = aSequence[i] 
     a = i 
     # use append to keep your items in the list to be returned 
     list1.append((a, b)) 
    return list1 

print(enum('hello')) # this should print horizontally like you asked. 

關於最簡單的答案來創建你想要的列表,枚舉函數是你的朋友。枚舉函數解開索引的一個元組以及在索引處找到的可迭代對象。

thing = 'hello there!' 

#typical use case for enumerate 
for i, item in enumerate(thing): 
    print(i, item) 

所以這裏有一個例子函數,你想要做什麼......

def enum(iterable): 
    # must use list() to cast it as an object or else we return a generator object 
    return list(enumerate(iterable)) 

enum('hello there!') 
相關問題