在python列表中打印特定项目 [英] Printing a specific Item in a python list
问题描述
我对 python 有点陌生,我只想知道如何打印列表中的单个元素.下面的例子是简单的列表.
I'm little bit new to the python and I just want to know how to print a single element in a list. as example below is simple list.
test_list = [['abc','2'],['cds','333']]
我想知道如何只打印abc"值.使用
I want to know how do I get print only the "abc" value. using the
print test_list[0:1]
它将显示为
[['abc', '2']]
推荐答案
test_list
是一个包含列表的列表.
test_list
is a list that contains lists.
Python list
允许随机访问,即你可以访问任何你想要的元素,只要你知道它的位置索引.
Python list
allows random access, i.e. you can access any element you want, providing you know its positional index.
例如,列表中的第一个元素是test_list[0]
,第二个元素是test_list[1]
.
For instance, the first element on the list is test_list[0]
, and the second is test_list[1]
.
同理,最后一个元素是test_list[-1]
,倒数第二个元素是test_list[-2]
.
In the same manner, the last element is test_list[-1]
, and the second-to-last element is 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])
这篇关于在python列表中打印特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!