简体   繁体   English

Python:访问特定的子列表元素

[英]Python: Accessing specific sublist element

Is there a way to be able to access specific sublist element?有没有办法能够访问特定的子列表元素?

For example:例如:

list = [["a","b"],["c","d"]]

how to print out only b ??如何只打印出b ??

Thanks!谢谢!

Firstly, it is a bad practice to name a variable as list as it is a keyword in Python.首先,将变量命名为list是一种不好的做法,因为它是 Python 中的关键字。 Say, it is changed to lis说,改成lis

lis = [["a","b"],["c","d"]]

To access b, you need to first get to the first element of lis , by lis[0] .要访问 b,您需要首先通过lis[0] lis的第一个元素。 This gives ["a", "b"] .这给出了["a", "b"] Now you need to further go into it, so you do lis[0][1] , This gives the 1-indexed element of lis[0] , ie, 'b'现在你需要进一步研究它,所以你做lis[0][1] ,这给出了lis[0]的 1-indexed 元素,即 'b'

You need to select the first sublist in your list (index 0), and then the second element of your sublist (index 1).您需要选择列表中的第一个子list (索引 0),然后选择子列表的第二个元素(索引 1)。

Result is list[0][1] .结果是list[0][1]

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

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