如何访问List元素

时间:2012-05-16 06:29:56

标签: python list

我有一个清单

list = [['vegas','London'],['US','UK']]

如何访问此列表的每个元素?

5 个答案:

答案 0 :(得分:24)

我首先不要调用它list,因为这是Python内置list类型的构造函数的名称。

但是一旦你将它重命名为cities或其他东西,你就会这样做:

print(cities[0][0], cities[1][0])
print(cities[0][1], cities[1][1])

答案 1 :(得分:3)

这很简单

y = [['vegas','London'],['US','UK']]

for x in y:
    for a in x:
        print(a)

答案 2 :(得分:1)

以艰难的方式学习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])

答案 3 :(得分:0)

用于打印列表中所有项目的递归解决方案:

def printItems(l):
   for i in l:
      if isinstance(i,list):
         printItems(i)
      else:
         print i


l = [['vegas','London'],['US','UK']]
printItems(l)

答案 4 :(得分:0)

尝试list[:][0]以显示列表中每个列表的所有第一成员均无效。结果在不知不觉中将与list[0][:]

所以我这样使用列表理解:

[i[0] for i in list]会为列表中的每个列表返回第一个元素值。

相关问题