当我在Python中创建数组列表并打印出第一个索引的结果时,为什么还要打印方括号呢?
people = [
["Fredrick", 23],
["Lorenzo", 13],
["Francesco", 13],
["Giovanna", 9]
]
print(f"{people[0]}")
输出:['Fredrick',23]
您定义了一个以数组为元素的数组。这就是为什么访问人数组的第一个索引时会得到数组['Fredrick',23]的原因。这等效于访问数组的第一项
>> array = [10, 20, 30]
>> print array[0]
>> 10
在您的情况下,第一个元素是数组:
>> ['Fredrick', 23]
一种替代方法可以是:
# map is another (more appropriate)
# data structure to store this data.
people = {
'Fredrick': 23,
'Lorenzo': 13,
'Francesco': 13,
'Giovanna': 9
}
for name, age in people.items():
# iterate through all map items
# and print out each person's name and age.
# Note: you need to convert the age from int to string
# in order to concatenate it.
print name + ", " + str(people[name])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句