Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
[-4:]在python中是什么意思?_Python_Nltk - Fatal编程技术网

[-4:]在python中是什么意思?

[-4:]在python中是什么意思?,python,nltk,Python,Nltk,我在课堂上了解到,对于Python,字符从[0]开始。例如,在Monty Python中,'M'=0,'o'=1,'n'=2,'t'=3,'y'=4,'5,'P'=6,'y'=7,'t'=8,'h'=9,'o'=10,'n'=11 但当我看到NLTK上的以下操作时,我感到困惑: genre_word = [(genre, word) for genre in ['news', 'romance'] for word in brown.wor

我在课堂上了解到,对于Python,字符从[0]开始。例如,在Monty Python中,'M'=0,'o'=1,'n'=2,'t'=3,'y'=4,'5,'P'=6,'y'=7,'t'=8,'h'=9,'o'=10,'n'=11

但当我看到NLTK上的以下操作时,我感到困惑:

genre_word = [(genre, word) for genre in ['news', 'romance']
                            for word in brown.words(categories=genre)]

genre_word[:4]
genre_word[-4:]

我以为所有字符编号都以[0]开头。[-4:]是什么意思?

对于python中的任何iterable[-4:]表示该iterable最后四项的索引。例如:

list1 = [1,2,3,4,5,6]
list1[-4:]
[3,4,5,6]

“世界”


它获取序列的最后四个元素:

>>> l = [1,2,3,4,5,6,7,8,9]
>>> l[-4:]
[6, 7, 8, 9]
>>> 

正如您在python中所说,数组的索引从0开始

让我们说

my_word = 'hello world'
print(my_word[0])  #prints 'h'
my_word = 'hello world'
print(my_word[-1]) # prints 'd'
# - stands from last starting with index 1
print(my_word[-4:]) # prints 'orld'
# if you know the length you can directly use
print(my_word[7:])  # prints 'orld'
在python中,我们还有一个从上一个

让我们说

my_word = 'hello world'
print(my_word[0])  #prints 'h'
my_word = 'hello world'
print(my_word[-1]) # prints 'd'
# - stands from last starting with index 1
print(my_word[-4:]) # prints 'orld'
# if you know the length you can directly use
print(my_word[7:])  # prints 'orld'

如果不知道长度,此功能可帮助您打印从最后一个元素开始的索引值

some_list[-n]语法可获取从最后一个元素开始的第n个元素。因此,一些_列表[-4]获取最后四个元素。