簡體   English   中英

無法在 Python 中創建我自己的“zip”函數

[英]Trouble creating my own "zip" function in Python

作為個人練習,我正在嘗試創建自己的小 zip() 函數,它接受兩個列表並將項目放入元組列表中。 換句話說,如果這些是我的清單:

fr = [6,5,4]
tr = [7,8,9]

我希望這樣:

[(6,7), (5,8), (4,9)]

這是我的代碼:

def zippy(x, y):
    zipper = []
    for i in x :
        for g in y:
            t = (i,g)
        zipper.append(t)

我得到的是: [(6, 9), (5, 9), (4, 9)] ,但是當我在函數內部定義列表時,它按預期工作。 任何幫助表示贊賞。

使用索引訪問相同索引的項目:

def zippy(x, y):
    zipper = []
    for i in range(len(x)):
        zipper.append((x[i], y[i]))
    return zipper

使用列表理解

def zippy(x, y):
    return [(x[i], y[i]) for i in range(len(x))]

>>> fr = [6,5,4]
>>> tr = [7,8,9]
>>> zippy(fr, tr)
[(6, 7), (5, 8), (4, 9)]

請考慮,如果您有兩個不同長度的列表,您的 zip 應該在最短序列結束時停止。 以下是如何操作的示例:

def zippy(x, y):
    iter1 = iter(x)
    iter2 = iter(y)
    while True:
        try:
            yield next(iter1), next(iter2)
        except StopIteration:
            return

要么

def zippy(x, y):
    iter1 = iter(x)
    iter2 = iter(y)
    for _ in range(min(len(x), len(y))):
        yield next(iter1), next(iter2)

另請注意,標准 zip 函數返回 (generator) 而不是數據列表:這意味着如果您需要從結果中獲取數據,則必須將 zip 結果轉換為列表:

result = zippy(fr, tr)
print(list(result))

或對其調用迭代器

next(result)

我建議使用range()循環遍歷數組的每個索引。 然后,將它們放在一個元組中並將它們附加到數組中。

def zippy(x, y):
    zipper = []
    for i in range(len(x)) :
        zipper.append((x[i],y[i]))
    return zipper

有關range()的更多信息,請訪問此處

您需要同時迭代兩個數組以從兩個數組中獲取相同的索引

 def zippy(x, y):
        zipper = []
        for i,g in zip(x,y):
            t = (i,g)
            zipper.append(t)
        print(zipper)

輸出

[(6, 7), (5, 8), (4, 9)]
# A zip() is a kind of map()!
def zippy(a, b):
  return map(lambda (i, a): (a, b[i]), enumerate(a))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM