【问题标题】:Creating a tuple using a for loop.使用 for 循环创建元组。
【发布时间】:2016-05-08 13:32:16
【问题描述】:

我是 Python 新手,虽然我对 Codecademy 进行了一些复习,但我在第一项任务中遇到了困难。

“任务1:请打开代码骨架文件“i772_assg1.py”并实现函数list_ele_idx(li)。你必须编写一个“for循环”来读取列表的元素,并为每个元素你创建一个元组 (element,index) 来记录列表中的元素及其索引(位置)。这个函数接受一个列表“li”作为它的参数。函数的返回值应该是一个列表(元素,索引) 元组。在 main 方法中,我为任务 1 编写了一个测试用例。请取消注释测试用例并测试您的功能。”

这是我正在尝试的,但我什么也没得到。任何反馈都将不胜感激,因为这是我在 Stack Overflow 上的第一篇文章!

def list_ele_idx(li):
    index = 0 # index
    element = [(5,3,2,6)]
    li = [] # initialze a list; you need to add a tuple that includes an element and its index to this list
    # your code here. You must use for loop to read items in li and add (item,index)tuples to the list lis
    for index in li:
        li.append((element, index))
    return li # return a list of tuples

【问题讨论】:

  • element = [(5,3,2,6)] 的行是给定的吗?
  • 您将li 作为参数然后忽略它。您将index 分配为零,然后使用index 作为循环变量将其丢弃。您正在循环一个空列表。您没有做任何事情来跟踪列表中的索引。
  • 不,没有给出。我们得到了一个框架代码,其中提供了“测试用例”作为 main 函数的定义。由于测试用例包含 [5,3,2,6],看起来像是列表的元素,因此我创建了一个列表变量“元素”。感谢您的回复!
  • @khelwood。就像我通过重新使用它们来重新分配'li'和'index'?现在我这么说,这听起来像是一个错误。 -_-

标签: python list for-loop tuples


【解决方案1】:

让我们逐步检查您的代码,以便您了解所犯的错误,然后让我们看看正确的解决方案。最后,让我们看看可能会惹恼老师的pythonic解决方案。

线

index = 0

很好,因为您想从零开始计算索引。线

element = [(5,3,2,6)]

没有意义,因为您的函数应该适用于任何给定的列表,而不仅仅是您的测试用例。所以让我们删除它。 你用

初始化你的结果列表
li = []

如果您不重复使用给定输入列表的名称li,那会很好,因为它会丢弃给函数的参数。使用

result = []

相反。接下来,您将使用

遍历您现在为空的列表 li
for index in li:

由于此时li 为空,循环体将永远不会执行。将循环变量命名为 index 会造成混淆,因为您使用该语法循环遍历列表的元素,而不是索引。

li.append((element, index))

在您的 for 循环内是错误的,因为您永远不会增加 index 并且 element 是一个列表,而不是您输入列表中的单个元素。

这是一个有效解决方案的注释版本:

def list_ele_idx(li):
    index = 0 # start counting at index 0
    result = [] # initialize an empty result list
    for item in li: # loop over the items of the input list
        result.append((item, index)) # append a tuple of the current item and the current index to the result
        index += 1 # increment the index
    return result # return the result list when the loop is finished

使用enumerate(li) 会给你一个更简单的解决方案,但我认为这不符合练习的精神。无论如何,简短的解决方案是:

def list_ele_idx(li):
    return [(y,x) for x,y in enumerate(li)]

【讨论】:

  • 这是提供答案的好方法! :-)
  • @timgeb 感谢您的描述性回复。我应该注意到的第一件事是循环变量缺少增量。我们得到了 'lis' 来代替你声明的变量 'result'。作为 Python 的新手,我认为这是一个错字,完全没有意识到在参数中使用 'li' 作为定义会丢弃它。谢谢!
  • @squidvision 如果此答案解决了您的问题,请务必联系mark it as accepted by clicking the check mark。这可以帮助任何未来的访问者向他们展示正确的答案。
【解决方案2】:

查看 Python 的 enumerate 函数,它为您提供要迭代的元素及其索引:

def list_ele_idx(li):
    tuple_list = []
    for index, item in enumerate(li):
        tuple_list.append((index, item))
    return tuple_list

【讨论】:

    猜你喜欢
    • 2013-03-17
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多