【问题标题】:Python 3: How to alter individual items in a list within a functionPython 3:如何更改函数内列表中的单个项目
【发布时间】:2018-01-29 15:35:50
【问题描述】:

我创建了一个魔术师姓名列表。我正在尝试将“The Great”添加到列表中的每个单独项目,同时永久更改列表格式。到目前为止,这是我的代码:

magician_names = ['houdini' , 'chris angel', 'ted']
def show_magicians():
    print("These are your magicians tonight.")
    while magician_names:
        print(magician_names)
        break
show_magicians()

def make_great():
    for name in magician_names:
            while True:
                ['The Great' , name]
                break
    print(magician_names)

我可以创建一个 for 循环和一个字符串来打印每个单独的名称,并在其前面使用“The Great”,如下所示:

for magician in magician_names:
    print("The Great " + magician)

打印这个结果:

The Great houdini
The Great chris angel
The Great ted

但是我想要它,所以当我调用函数并打印列表“magician_names”时,它会打印出列表的更改版本,格式如下:

['the great houdini' , 'the great chris angel', 'the great ted']

【问题讨论】:

  • 不知道你到底在做什么,但你把一个简单的问题复杂化了。列表是 Python 中的可变数据结构,因此您需要做的就是使用字符串连接和列表迭代。
  • new 字符串替换列表中的每个项目,或者用新字符串创建一个新列表。
  • 花点时间和the Tutorial一起练习例子。它将让您了解 Python 提供的帮助您解决问题的工具。
  • while magician_names: print(magician_names) break 的意义何在? print(magician_names) 也一样。

标签: python python-3.x list function


【解决方案1】:

这给出了嘲笑的输出:

magician_names = ['houdini' , 'chris angel', 'ted']
l = ['The Great ' + name for name in magician_names]
print(l)

【讨论】:

  • 我刚刚用该代码更新了列表并且它可以工作。但是每当我尝试在一个函数中运行它时,它都会返回一个错误,说“局部变量:在赋值之前引用'magician_names'”。
  • @drewmende 我假设magician_names,在该函数中是未知的,但这只是一个猜测,因为我没有代码。也许您可以尝试将其作为参数传递给函数。
【解决方案2】:

谢谢你的帮助,我终于明白了。我把这段代码放在第二个函数中,当这两个函数都被调用时,代码会按需要运行。:

for i in range(0, len(magician_names)):
        magician_names[i] = "The Great " + magician_names[i]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多