繁体   English   中英

Python 嵌套列表中的第二个参数是什么意思?

[英]What means the second parameter in a Python nested list?

我建立了一个这样的嵌套列表

List1 = ["Smith", "John", "Boston"]
List2 = ["Brown", "Jim", "New York"]
customers = [[List1], [List2]]
print(customers)

[[['史密斯','约翰','波士顿']],[['布朗','吉姆','纽约']]]

要访问列表的元素,我必须添加第二个参数,我不明白。

i=0 
while i<=len(customers)-1:
    print(customers[i][0][0], customers[i][0][1], customers[i][0][2])
    i+=1

史密斯约翰波士顿布朗吉姆纽约

为什么中间有[0]? 为什么不简单地 [i][1]? 你能帮助我吗?

因为您正在创建列表列表

customers = [[List1], [[List2]]

如果你写了customers = [List1, List2]那么就不需要中间索引。

List1 = ["Smith", "John", "Boston"]
List2 = ["Brown", "Jim", "New York"]
customers = [List1, List2]
print(customers)

[['Smith', 'John', 'Boston'], ['Brown', 'Jim', 'New York']]

i=0
while i<=len(customers)-1:
    print(customers[i][0], customers[i][1], customers[i][2])
    i+=1

Smith John Boston
Brown Jim New York

基础

  • a = ["Smith", "John", "Boston"]是一个列表。 您可以通过a[0]访问它的第一项
  • b = [a]b = [["Smith", "John", "Boston"]]相同,这是一个列表。
    • b[0] : 将是列表的第一项["Smith", "John", "Boston"]
    • b[0][0] :将是第一个项目的第一个项目,这将是Smith
    • b[0][0][0] :将是第一项的第一项的第一项,这将是S
  • b = [[a]]b = [[["Smith", "John", "Boston"]]]相同,它是一个列表列表(3 个嵌套列表)。
    • b[i][j][k] :将返回 b 中第i个 position 的第j个项目的第k个项目,因此b b[0][0][0]将返回第一项的第一项的第一项b 是Smith

暂无
暂无

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

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