我有一个列表
list = [['vegas','London'],['US','UK']]
如何访问此列表中的每个元素?
首先,我会建议你不要将其命名为list
,因为这是Python内置的list
类型的构造函数名称。
但一旦你将其重命名为cities
或其他名称,你可以这样做:
print(cities[0][0], cities[1][0])
print(cities[0][1], cities[1][1])
这很简单
y = [['vegas','London'],['US','UK']]
for x in y:
for a in x:
print(a)
尝试使用list[:][0]
来显示列表中每个列表的第一个成员未能成功。结果将与list[0][:]
相同。
因此我使用了列表推导式,如下所示:
print([i[0] for i in list])
该函数返回列表中每个子列表的第一个元素值。
PS:由于该问题中使用了变量名list
,因此我不会将其用作变量名,因为在Python中它是基本函数list()
的名称。
学习Python的艰难方式 ex 34
尝试这个
animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus']
# print "The first (1st) animal is at 0 and is a bear."
for i in range(len(animals)):
print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i])
# "The animal at 0 is the 1st animal and is a bear."
for i in range(len(animals)):
print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i])
递归解决方案以打印列表中的所有项目:
def printItems(l):
for i in l:
if isinstance(i,list):
printItems(i)
else:
print i
l = [['vegas','London'],['US','UK']]
printItems(l)
cities = {"Vegas": "US", "London": "UK"}
。 - Tim Pietzckerdir()
中不属于您的任何内容。 - Countour-Integral