【问题标题】:How to reverse order a list? (Python 3.x) [duplicate]如何反转列表的顺序? (Python 3.x)[重复]
【发布时间】:2016-06-29 11:16:56
【问题描述】:

如何反转包含 def view(self) 的字符串的列表,因为使用 reversed() 我得到一个错误,它不能用字符串完成。有什么帮助吗?

class Stack():

    def __init__(self):
        self.stack = []

    def view(self):
        for x in reversed(self.stack):
            print(self.stack[x])

    def push(self):
        item = input("Please enter the item you wish to add to the stack: ")
        self.stack.append(item)

    def pop(self):
        item = self.stack.pop(-1)
        print("You just removed item: {0}".format(item))

stack = Stack()

【问题讨论】:

  • 有什么理由在view 中没有简单的print(x)

标签: python-3.x


【解决方案1】:

for x in list(...): 将 x 设置为列表的每个元素。您可能会将其与遍历字典混淆,其中 x 将设置为每个元素的键。

def view(self):
    for x in reversed(self.stack):
        print(x)

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 2020-12-05
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2012-09-08
    • 1970-01-01
    相关资源
    最近更新 更多