0

我正在尝试使用 while 循环从 python 中的列表中读取,但我似乎无法得到它。我不断收到列表索引超出范围错误。

这是列表:

names = [['Bilbo', 'Baggins'], ['Gollum'], ['Tom', 'Bombadil'], ['Aragorn']]

而不是使用 for 循环:

for person in people:     
    to_print = "" 
    for name in person: 
        to_print += name + " " 
    print(to_print)
4

3 回答 3

1

要使用 Python 列表,您不需要索引。

for bunch_of_names in names:
    if len(bunch_of_names) > 1: # e.g. bunch_of_names = ['Bilbo', 'Baggins']
        print 'First name:', bunch_of_names[0], 'Last name: ', bunch_of_names[1]
    else: # e.g. ['Aragorn']
        print 'Name: ', bunch_of_names[0] # the only one
于 2013-04-26T01:44:51.270 回答
1

循环代码的等效while循环版本for是:

>>> i = 0
>>> while i < len(names):
        j = 0
        to_print = ""
        while j < len(names[i]):
            to_print += names[i][j] + " "
            j += 1
        print(to_print)
        i += 1


Bilbo Baggins 
Gollum 
Tom Bombadil 
Aragorn 

更好的for循环代码版本是:

>>> for person in names:
        print(' '.join(person))


Bilbo Baggins
Gollum
Tom Bombadil
Aragorn
于 2013-04-26T01:58:23.710 回答
0

这样的事情怎么样?

for name in names:
   for subname in name:
       print(subname)
于 2013-04-26T01:43:04.403 回答