在Python中,如何打印列表中的值

Jia*_*eng 2 python python-3.x

我想从列表中打印出某个值。这是我的代码:

rdf_f = open("substrate.txt")
for line in rdf_f:
    fields = line.split()
    if len(fields) > 1:
        x = fields[1]
    print(x[2])
Run Code Online (Sandbox Code Playgroud)

如何正确使用print()命令打印出 的第三个值x?因为我收到一个错误:

IndexError: string index out of range
Run Code Online (Sandbox Code Playgroud)

我知道x = [1,2,3,4,5,6]我的代码是否有效。但这里x是一个垂直的柱子。当我使用时print(x),输出是

0
1
2
3
4
5
6
7
8
9
10
0
1
2
3
4
5
6
7
8
9
10
...
Run Code Online (Sandbox Code Playgroud)

Sri*_*thy 5

您收到该错误是因为该索引处没有任何项目。所以你最好使用for循环。并打印所有项目。

for item in fields:
    print item
Run Code Online (Sandbox Code Playgroud)

或者

检查字段列表的长度并相应地打印。

   if len(fields)>3:
      print fields[3]
Run Code Online (Sandbox Code Playgroud)