使用函数和 for 循环反转列表项的内部顺序。

Reversing inner sequence of list items using a function and for loop.

我需要帮助来理解一项给我带来很多麻烦的家庭作业。我尝试了许多不同的方法来获得以下分配以产生所需的结果:

  1. Create a module named task_05.py
  2. Create a function named flip_keys() that takes one argument: a. A list named to_flip. This list is assumed to have nested, immutable sequences inside it, eg: [(1, 2, 3), 'hello']
  3. Use a for loop to loop the list and reverse the order of the inner sequence. All operations on the outer list must operate on the original object, taking advantage of its mutability. Inner elements are immutable and will require replacement.
  4. The function should return the original list with its inner elements reversed.

我的教授将通过将以下内容输入 python shell:

来评估我的脚本的结果
>>> LIST = [(1, 2, 3), 'abc']
>>> NEW = flip_keys(LIST)
>>> LIST is NEW
True
>>> print LIST
[(3, 2, 1), 'cba']

我不知道我做错了什么,我的教授也没有回应。学生们也没有回应,我已经多次查看 material 以试图找到答案。我的脑子里有什么东西没有发出咔哒声。

他提供了以下提示,我相信我已经在我的脚本中实现了这些提示:

Hint

Consider how to access or change the value of a list. You did it already in task 2!

Hint

In order to change the value in to_flip you'll need some way to know which index you're attempting to change. To do-this, create a variable to act as a counter and increment it within your loop, eg:

counter = 0 for value in iterable_object:

do something counter += 1 Now consider what that counter could represent. At the end of this loop does counter ==

len(iterable_object)

Hint

For an idea on how to reverse a tuple, head back to an earlier assignment when you reversed a string using the slice syntax.

这是我最新的没有评论的脚本(因为在脚本运行之前我不会写它们):

def flip_keys(to_flip):
    for loop_list in to_flip:
        to_flip = [to_flip[0][::-1], to_flip[1][::-1]]
        return to_flip

当我使用上面粘贴的命令测试脚本时,我得到了这些结果:

>>>LIST = [(1, 2, 3), 'abc']
>>>NEW = flip_keys(LIST)
>>>LIST is NEW 
False
>>>print flip_keys(LIST) 
[(3, 2, 1), 'cba']
>>>print LIST 
[(1, 2, 3), 'abc']

作业的目标是体验可变性,我想我明白了。我面临的问题是 LIST 变量应该由函数更新,但这从未发生过。

以下应该计算为 True,而不是 False。然后打印存储在 LIST 常量中的反转列表值。

>>>LIST = [(1, 2, 3), 'abc']
>>>NEW = flip_keys(LIST)
>>>LIST is NEW False

请告诉我这些信息是否足够。我在这上面花了太多时间,此时我的作业迟到了 4 天,而且我没有得到教授或学生的支持(我已经通知了我的导师)。

您正在从您的函数返回一个新列表。使用完整切片 [:] 赋值对原始列表进行 就地 突变。

您还可以使用更传统的方式来创建列表 - 列表理解 - 而不是 for 循环:

def flip_keys(to_flip):
    to_flip[:] = [i[::-1] for i in to_flip]
    return to_flip

测试

>>> LIST = [(1, 2, 3), 'abc']
>>> NEW = flip_keys(LIST)
>>> NEW
[(3, 2, 1), 'cba']
>>> NEW is LIST
True

IMO,改变一个可变参数并返回它感觉不到 right/conventional。这可以在您的下一个 class.

中进行很好的讨论