【问题标题】:Iterating within a function在函数内迭代
【发布时间】:2012-10-04 09:47:24
【问题描述】:

我整天都在努力,但没有成功,我花了大约 4 个小时来研究可能的答案,因为我喜欢自己发现东西,但我似乎无法更进一步。

我正在编写一个接受字符串的函数,并且我必须使用这个字符串将每个字符转换为一个符号,不包括空格和破折号。

我也尝试为它创建一个银行系统,但它似乎只迭代第一个元素,这与 return 有关吗?

def get_view(puzzle): 
  for elements in puzzle:
      new_ string = elements.replace(elements, "$")
      return new_string 

编辑: 我试过了:

隐藏 = "^" new_string = ""

def get_view(puzzle):
    for elements in puzzle:
    new_string = puzzle.replace(elements, HIDDEN)
    return new_string                  

现在又回来了

get_view("abc") 'ab^'

Wtttfffff。

【问题讨论】:

  • 哇,this assignment 应该在今天到期!?
  • 不,这周到期。我刚接触编程,想了解正在发生的事情。
  • 哈哈有趣,他没有上我的学校,但我敢肯定大多数 Python 入门课程都有相同的材料。

标签: python function iteration


【解决方案1】:

首先,您必须定义要将每个字母转换为的内容。举个例子吧

conversion_symbols = {'a':'$','b':'#'}#其余部分自己填写。

# then you have to loop over the string, give gives one character at a time, covert it and
# and add to your result string and then return the result string.

def get_view(puzzle):
  new_string = ""
  for element in puzzle:
      new_string += conversion_symbols[element]
  return new_string

这是您尝试采用的方法吗?

【讨论】:

  • 当我尝试得到错误:文件“”,第 1 行,在 get_view("abc") 文件“”,第 16 行, 在 get_view new_string += HIDDEN[element] TypeError: string indices must be integers END where HIDDEN is defined replacement.
  • HIDDEN = "^" def get_view(puzzle): new_string = "" for element in puzzle: new_string += HIDDEN[element] return new_string 这是我在出现错误时使用的代码跨度>
【解决方案2】:

它确实与return 有关。当遇到return 语句时,函数进程终止;因此,您的函数的 for-loop 将始终在其第一次迭代时结束。

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多