簡體   English   中英

如何使用 Python 3.5.1 從列表中打印多個非連續值

[英]How to print multiple non-consecutive values from a list with Python 3.5.1

我創建了一個列表,想從列表中選擇一些要打印的項目。 下面,我只想打印出索引 0 處的“熊”和索引 3 處的“袋鼠”。我的語法不正確:

>>> animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
>>> print (animals[0,3])

回溯(最近一次調用):文件“”,第 1 行,打印中(動物 [0,3])類型錯誤:列表索引必須是整數或切片,而不是元組

我嘗試在索引之間留一個空格,但它仍然給出錯誤:

>>> print (animals[0, 3])

回溯(最近一次調用):文件“”,第 1 行,打印中(動物 [0, 3])類型錯誤:列表索引必須是整數或切片,而不是元組

我可以打印單個值或 0-3 的范圍,例如:

>>> print (animals [1:4])
['python', 'peacock', 'kangaroo']

如何打印多個不連續的列表元素?

要從列表中選擇任意項目,您可以使用operator.itemgetter

>>> from operator import itemgetter    
>>> print(*itemgetter(0, 3)(animals))
bear kangaroo
>>> print(*itemgetter(0, 5, 3)(animals))
bear platypus kangaroo

Python 的list類型不支持使用animals[0,3]的元組進行切片。 如果您想要某些任意值,則必須分別對它們進行索引。

print(animals[0], animals[3])

list(animals[x] for x in (0,3))是你想要的子集。 與 numpy 數組不同,原生 Python 列表不接受列表作為索引。

您需要將生成器表達式包裝在list以打印它,因為它本身沒有可接受的__str____repr__ 您也可以使用str.join來獲得可接受的效果: ', '.join(animals[x] for x in (0,3))

默認情況下,Python 的列表類型不支持。 返回一個切片對象,表示由 range(start, stop, step) 指定的索引集。

class slice(start, stop[, step])

>>>animals[0:5:2]
['bear', 'peacock', 'whale']

創建一個子類以自己實現或間接獲取指定的值。 例如:

>>>map(animals.__getitem__, [0,3])
['bear', 'kangaroo']
print(animals[0] + " " + animals[3] + " " + ...)

暫無
暫無

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

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