簡體   English   中英

使用“for”循環和使用星號運算符 (*) 解包在 Python 中打印元組

[英]Printing a tuple in Python using both "for" loop and unpacking with star operator (*)

我正在嘗試以兩種不同的方式在以下代碼中打印“結果”元組的項目:

  • 使用“for”循環
  • 在 print() 方法中使用星號運算符

在輸出中,字符串 "reference point" 應該將兩種方式的結果分開。

animals = {"dog", "cat", "pig"}
numbers = (1, 2, 3)
column = ['a', 'b', 'c']
result = zip(animals, column, numbers)

#first way of printing the items in the result tuple
for item in result:
    print(item)

print('\nreference point\n')

#second way of printing the items in the result tuple
print(*result, sep="\n")

但是,代碼只輸出第一個結果(在“參考點”之前),無論這是哪種方式(“for”循環或星號運算符),如下所示:

('dog', 'a', 1)
('pig', 'b', 2)
('cat', 'c', 3)

reference point

有誰知道為什么“結果”元組的項目只打印一次以及如何解決這個問題? 我正在尋找如下輸出:

('dog', 'a', 1)
('pig', 'b', 2)
('cat', 'c', 3)

reference point

('dog', 'a', 1)
('pig', 'b', 2)
('cat', 'c', 3)

zip構建的迭代器在第一次迭代時就耗盡了,需要重新構建或者做成一個列表,比如result = list(zip(animals, column, numbers))

暫無
暫無

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

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