在 python 中,有没有办法在不创建自定义函数的情况下将整数列表列表转换为字符串列表列表?

In python, is there a way to convert of list of integer-lists into a list of string-lists without creating a custom function?

假设我有一个整数列表列表:

start=[[1,2,3],[4,5,6],[7,8,9]]

我想将其转换为:

result=[["1","2","3"],["4","5","6"],["7","8","9"]]

我可以通过创建自己的函数来解决这个问题。有没有不用自定义函数的方法解决?

def stringify(x):
     return map(str,x)

start = [[1,2,3],[4,5,6],[7,8,9]]

result = map(stringify,start)

您可以使用 map() in combination with list comprehension,像这样:

result = [map(str, lst) for lst in start]

如果您知道数组是规则的(即所有行的长度都相同),您也可以这样做

result = numpy.array(start, dtype=str)

当然 returns 一个 numpy 数组,而不是列表。

为了让它尽可能像 pythonic,我会写:

result = [[str(subitem) for subitem in sublist] for sublist in start]

IMO,编写最易读的代码总是更好,list-comprehensions are sometimes faster than map