在 Python 中,假設我想從字典中獲取 N 個任意項——比如說,列印它們,檢查一些項。我不在乎我得到了哪些物品。我不想把字典變成一個串列(就像我看到的一些代碼一樣);這似乎是一種浪費。我可以使用以下代碼(其中 N = 5)來做到這一點,但似乎必須有一種更 Pythonic 的方式:
count = 0
for item in my_dict.items():
if count >= 5:
break
print(item)
count = 1
提前致謝!
uj5u.com熱心網友回復:
您可以使用itertools.islice切片任何可迭代物件(不僅是串列):
>>> import itertools
>>> my_dict = {i: i for i in range(10)}
>>> list(itertools.islice(my_dict.items(), 5))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
uj5u.com熱心網友回復:
我可能會使用zipand range:
>>> my_dict = {i: i for i in range(10)}
>>> for _, item in zip(range(5), my_dict.items()):
... print(item)
...
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
這里的唯一目的range是提供一個可zip在 5 次迭代后停止的可迭代物件。
uj5u.com熱心網友回復:
您可以稍微修改一下:
for count, item in enumerate(dict.items()):
if count >= 5:
break
print(item)
注意:在這種情況下,當您遍歷 .items() 時,您將獲得一個鍵/值對,可以在迭代時對其進行解包:
for count, (key, value) in enumerate(dict.items()):
if count >= 5:
break
print(f"{key=} {value=})
如果你只想要鍵,你可以遍歷字典。
for count, key in enumerate(dict):
if count >= 5:
break
print(f"{key=})
如果您只想要這些值:
for count, value in enumerate(dict.values()):
if count >= 5:
break
print(f"{value=})
最后一點:使用dict作為變數名會覆寫內置dict并使其在您的代碼中不可用。
uj5u.com熱心網友回復:
通常,我想使用切片表示法來執行此操作,但dict.items()回傳一個不可切片的迭代器。
您有兩個主要選擇:
- 讓它成為切片符號適用的東西:
x = {'a':1, 'b':2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
for item, index in list(x.items())[:5]:
print(item)
- 使用適用于迭代器的東西。在這種情況下,內置的(并且非常流行的 itertools 包)
import itertools
x = {'a':1, 'b':2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
for item in itertools.islice(x, 5):
print(item)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451066.html
