[英]Select certain elements from a list in python
我認為這個問題之前已經被問過,盡管我找不到完全符合我的查詢的答案。
我想打印列表中的某些元素,具體取決於輸入的長度。 例子:
if anagramLength == 2:
print(words[0,5])
I found a think called 'operator.itemgetter' , although this selects individual elements, where as I want it to select all from position 0 TO position 5 (not position 0 AND position 5).
謝謝!
只需進行正確的切片:
words[0:5]
也就是說,將,
替換為:
if anagramLength == 2:
print(words[0:5])
使用words[0,5]
會產生錯誤:
TypeError: string indices must be integers
要了解導致錯誤的原因,請執行以下操作:
>>> 0,5
(0, 5)
看,它是一個tuple
。 您不能使用元組對字符串進行切片,而是使用 integer :)
您可以使用slicing
:
if anagramLength == 2:
print(words[:5])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.