在没有for循环的情况下改变列表中的列表(python 3)

时间:2017-02-07 21:27:54

标签: python list python-3.x nested

我试图改变" "的任何实例来打印-:所以我开始创建一个只在新行的列表中打印列表的函数:

def print_board(b):
    print("\n".join(map(lambda x:"".join(map(str, x)),b)))

前:

>>> print_board([[1,2,3],[2,3,4,5],[2,3,4]]
123
2345
234

然后我尝试使用这种类似的方法将列表中" "的每个实例变为-

def is_empty(b0):
    if b0 == " ":
        return "-"
    else:
        return b0

def empty_space(b):
    list(map(lambda x: list(map(is_empty, x)), b))#empty_space just mutates b

def check(b):
    _board = empty_space(b)
    return print_board(_board) #check just prints the mutated list b

我希望check(b)能够做到这一点,例如:

>>> check([[" ",3,4],[5,6,3],[" ", " ", " "]])
-34
563
---

但我收到了一个错误。我不介意使用递归而不是map和lambda,但我不想在任何这些函数中使用for循环。

2 个答案:

答案 0 :(得分:2)

我能想到的唯一解决方案是明确地使用for循环是将新列表复制到您已经获得的引用中:

def empty_space(b):
    b[:] = map(lambda x: list(map(is_empty, x)), b)

这实际上会更改传递给b的引用empty_space以获得映射器生成的值,此外不需要list调用,因为右侧可以是任何可迭代的。

您还应将check更改为:

def check(b):
    empty_space(b)
    print_board(b)

因为你没有找回任何价值。

现在按要求执行:

>>> check([[" ",3,4],[5,6,3],[" ", " ", " "]])
-34
563
---

b[:]最后会循环(必须),我真的没有看到为什么你觉得有必要排除for循环,但我想你必须有你的理由。

答案 1 :(得分:1)

如果只使用2D列表,则不需要递归。我知道您写道,您不想使用任何for loop,但map只不过是伪装的for loop。它也不会改变列表。

所以你需要的只是:

def check(rows):
    for row in rows:
        print "".join([str(x) for x in row]).replace(' ','-')

check([[" ",3,4],[5,6,3],[" ", " ", " "]])
# -34
# 563
# ---

如果你真的想使用map s:

def replace_char(char):
  return str(char).replace(' ', '-')

def replace_row(row):
  return "".join(map(replace_char, row))

def check(rows):
  print "\n".join(map(replace_row, rows))

check([[" ",3,4],[5,6,3],[" ", " ", " "]])
# -34
# 563
# ---