Python 从列表中读取
我试图使用while循环从python的列表中读取数据,但似乎无法得到它。我不断得到列表索引超出范围的错误 名单如下:Python 从列表中读取,python,list,Python,List,我试图使用while循环从python的列表中读取数据,但似乎无法得到它。我不断得到列表索引超出范围的错误 名单如下: names = [['Bilbo', 'Baggins'], ['Gollum'], ['Tom', 'Bombadil'], ['Aragorn']] 而不是将for循环用于: for person in people: to_print = "" for name in person: to_print += name + "
names = [['Bilbo', 'Baggins'], ['Gollum'], ['Tom', 'Bombadil'], ['Aragorn']]
而不是将for循环用于:
for person in people:
to_print = ""
for name in person:
to_print += name + " "
print(to_print)
像这样的怎么样
for name in names:
for subname in name:
print(subname)
要使用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
而循环代码的循环版本的对应的循环代码是:
>>> 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 person in names:
print(' '.join(person))
Bilbo Baggins
Gollum
Tom Bombadil
Aragorn
请显示您的代码保护IP:不要使用while循环从列表中获取数据。用于循环:
用于名称中的名称:print(名称[0])
记住索引介于0和len(名称)-1之间。我需要使用while循环。最初的工作是将for循环转换为while循环loops@user2322049你甚至还没有解释你想做什么,谢谢。我现在可以清楚地看出我错在哪里了。非常感谢苏