简体   繁体   English

使用双方括号访问列表元素(python)

[英]Accessing list elements using double square brackets (python)

given a list, such as:给定一个列表,例如:

programming_languages = ['Python', 'Perl', 'R', 'Ruby']

What are the rules for using double square brackets []?双方括号[]的使用规则是什么?

What I mean is if I try accessing programming_languages[2][0] or programming_languages[3][0] or programming_languages[-1][-4] for example, I'll get the element 'R'.我的意思是,如果我尝试访问programming_languages[2][0]programming_languages[3][0]programming_languages[-1][-4] ,我将获得元素“R”。

Thanks in advance for the help on clearing this up for me!在此先感谢您帮助我解决这个问题!

Edit: For some reason I did not realise the 'R' I get while accessing programming_languages[3][0] or programming_languages[-1][-4] is actually the 1st character of the 4th element in the list, and NOT the 2nd element 'R'.编辑:出于某种原因,我没有意识到访问programming_languages[3][0]programming_languages[-1][-4]时得到的“R”实际上是列表中第四个元素的第一个字符,而不是第二个元素“R”。 Thanks for the answers below!感谢您在下面的回答!

The square bracket operator isn't only defined on arrays, but also on strings.方括号运算符不仅定义在 arrays 上,还定义在字符串上。

a = programming_languages[1] # a = 'Perl'
print(a[0]) # P, which is the 0th letter of the string
print(a[3]) # l, which is the 3rd letter of the string

programming_languages is an array, so you are accessing each elemnt inside the array by first bracket, eg. programming_languages 是一个数组,因此您可以通过第一个括号访问数组中的每个元素,例如。 : programming_languages[0] which returns 'Python' . : programming_languages[0]返回'Python' noe in python, strings are considers as an array of characters, so the second bracket is picking the character whiting that string, so eg: programming_languages[0][0] returns 'P' noe in python,字符串被认为是一个字符数组,所以第二个括号是选择那个字符串的字符,所以例如: programming_languages[0][0]返回'P'

The square bracket syntax, like programming_languages[n] allow you to access the nth element.方括号语法,如programming_languages[n]允许您访问第n 个元素。

programming_languages = ['Python', 'Perl', 'R', 'Ruby']
programming_languages[0] # getting the first element in the list
# Python

When you use double square bracket, it means your element is a list-like object. If the first elements is Python then the first element would be P当你使用双方括号时,这意味着你的元素是一个类似列表的 object。如果第一个元素是Python那么第一个元素将是P

>>> programming_languages = ['Python', 'Perl', 'R', 'Ruby']
>>> # getting the first element in the list
>>> programming_languages[0] 
 Python
>>> # getting the first element in the string 'Python'
>>> programming_languages[0][0] 
 P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM