简体   繁体   English

在python列表中打印特定项目

[英]Printing a specific Item in a python list

I'm little bit new to the python and I just want to know how to print a single element in a list. 我对python有点陌生,我只想知道如何在列表中打印单个元素。 as example below is simple list. 下面的示例是简单列表。

test_list = [['abc','2'],['cds','333']]

I want to know how do I get print only the "abc" value. 我想知道如何仅打印“ abc”值。 using the 使用

print test_list[0:1]

it will show as 它会显示为

[['abc', '2']]

test_list is a list that contains lists. test_list是一个包含列表的列表。

Python list allows random access, ie you can access any element you want, providing you know its positional index. Python list允许随机访问,即,只要您知道其位置索引,就可以访问所需的任何元素。

For instance, the first element on the list is test_list[0] , and the second is test_list[1] . 例如,列表上的第一个元素是test_list[0] ,第二个test_list[1]test_list[1]

In the same manner, the last element is test_list[-1] , and the second-to-last element is test_list[-2] . 同样,最后一个元素是test_list[-1] ,倒数第二个元素是test_list[-2]

In your example, you want the first element of the first list, so you can do: 在您的示例中,您需要第一个列表的第一个元素,因此您可以执行以下操作:

first_list = test_list[0]
first_element = first_list[0]
print(first_element)

Or alternatively, you can get rid of all those temporary variables: 或者,您可以摆脱所有这些临时变量:

print(test_list[0][0])

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

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