使用for循环创建一个元组。

鱿鱼

我是Python的新手,虽然我在Codecademy上做了一些复习,但在执行第一个任务时遇到了困难。

“任务1:请打开代码框架文件“ i772_assg1.py”并实现函数list_ele_idx(li)。您必须编写一个“ for循环”来读取列表的元素,并为每个元素创建一个元组(元素,index)将元素及其索引(位置)记录在列表中,此函数以列表“ li”为参数,该函数的返回值应为(元素,索引)元组的列表。方法,我已经为任务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
提格布

让我们一步一步地遍历代码,以便您了解所犯的错误,然后看一下正确的解决方案。最后,让我们看一下可能困扰您的老师的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)]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章