本文介绍了列表索引如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题在python中:

This question is in python:

battleships = [['0','p','0','s'],
               ['0','p','0','s'],
               ['p','p','0','s'],
               ['0','0','0','0']]
def fun(a,b,bships): 
    c = len(bships)
    return bships[c-b][a-1]

print(fun(1,1,battleships))
print(fun(1,2,battleships))

第一次打印给出0
第二次打印给出p

first print gives 0second print gives p

我可以'弄清楚为什么,如果你能给出解释,我将不胜感激。

I can't work out why, if you could give an explanation it would be much appreciated.

感谢那些帮助的人:)

Thank you to those who help :)

推荐答案

索引从 0 开始。战舰包含索引 0 1 2 的物品, 3

Indexing starts at 0. So battleships contains items at indexes 0, 1, 2, 3.

首先 len(bships)获取列表清单的长度战舰,即4。

First len(bships) gets the length of the list of lists battleships, which is 4.

bships [cb ] [a-1] 通过索引值访问列表中的项目。所以第一次打电话给这个功能:

bships[c-b][a-1] accesses items in a list through their index value. So with your first call to the function:

print(fun(1,1,battleships))

这是 bships [4-1] [1-1] 这是 bships [3] [0] 这是 ['0','0','0','0'] [0] 这是 0

这篇关于列表索引如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 13:47