如何打印此列表中的第二个元素?

Abd*_*put -1 python

friends = ["John", "Mark", "James"]
for friend in friends:
    print(friend)
Run Code Online (Sandbox Code Playgroud)

如何使用 for 循环打印此列表中的第二个元素?我知道如何获取列表中的第二个元素,但我不知道如何使用for循环获取它。

U10*_*ard 6

你可以这样做:

print(friends[1])
Run Code Online (Sandbox Code Playgroud)

这将给出第二个元素,它将输出:

Mark
Run Code Online (Sandbox Code Playgroud)

如果要使用循环,请尝试:

for i, v in enumerate(friends):
    if i == 1:
        print(v)
Run Code Online (Sandbox Code Playgroud)

输出:

Mark
Run Code Online (Sandbox Code Playgroud)

Python 索引从 0 开始,因此第二个元素的索引将为 1。

我所做的 for 循环遍历列表,但迭代器i是每个元素的索引,并且v是值,因此它检查i(索引)是否为1,如果是,则打印v