【发布时间】:2017-02-17 03:05:32
【问题描述】:
我想使用 for 循环在列表列表中查找列表。
为什么它返回列表 0 而不是列表 2?
def make_str_from_row(board, row_index):
""" (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['H', 'O', 'U', 'S', 'E'], ['B', 'E', 'D'], ['C', 'H', 'E', 'E', 'S', 'E']], 2)
'CHEESE'
"""
letter = ''
line = ''
for row_index in board:
for letter in row_index:
line = line + letter
return line
make_str_from_row([['H', 'O', 'U', 'S', 'E'], ['B', 'E', 'D'], ['C', 'H', 'E', 'E', 'S', 'E']], 2)
【问题讨论】:
-
摆脱你的外循环。为您的内部循环执行
for letter in board[row_index]:。或者摆脱所有循环,只使用return ''.join(board[row_index])。 -
感谢@StevenRumbalski 非常清晰、简洁的解释!
标签: python list python-3.x for-loop