为什么这个将列表中的所有项目转换为字符串的函数不起作用?
Why does this function to convert all items in a list to strings not work?
我有一个二维数组,我尝试将每个数组中的所有项都转换为字符串。
首先我尝试使用一个函数 to_str
但这种方法没有用。我不明白为什么它不起作用(returns 输入不变):
lst = [['test1', 555], ['test2', 3333]]
def to_str(item):
for i in item:
if not isinstance(i, str):
i = str(i)
return item
output = list(map(lambda item:to_str(item), lst))
output: [['test1', 555], ['test2', 3333]]
然后我改用列表推导式,它起作用了:
output = list(map(lambda item: [str(i) for i in item], lst))
output: [['test1', '555'], ['test2', '3333']]
为什么使用 to_str
的第一种方法不起作用?
方法 #1 中的任何地方都没有使用转换后的值 i 并且函数只是 returns 输入
def to_str(item):
result = []
for i in item:
if not isinstance(i, str):
i = str(i)
result.append(i)
return result
您正在尝试修改名为 i
的迭代变量。这根本没有效果,您只是重写了指向列表元素的局部变量的值,而不是更改列表本身。为此,您必须修改每个索引位置的列表元素,如下所示:
def to_str(item):
# iterate over the indexes in the item
for i in range(len(item)):
# we can remove this check, and simply convert everything to str
if not isinstance(item[i], str):
item[i] = str(item[i])
return item
或者我们可以用结果创建一个新列表,而不是覆盖原来的列表(但这等同于使用列表推导,最好使用列表推导):
def to_str(item):
result = []
for element in item:
# we can remove this check, and simply convert everything to str
if not isinstance(element, str):
result.append(str(element))
else:
result.append(element)
return result
此外,关于您的第二种方法:最好避免使用 list
、map
和 lambda
,如果您想要创建一个新列表作为结果直接使用列表理解。这是解决问题的更惯用的方法,同时删除了不必要的字符串检查:
[[str(i) for i in item] for item in lst]
=> [['test1', '555'], ['test2', '3333']]
我有一个二维数组,我尝试将每个数组中的所有项都转换为字符串。
首先我尝试使用一个函数 to_str
但这种方法没有用。我不明白为什么它不起作用(returns 输入不变):
lst = [['test1', 555], ['test2', 3333]]
def to_str(item):
for i in item:
if not isinstance(i, str):
i = str(i)
return item
output = list(map(lambda item:to_str(item), lst))
output: [['test1', 555], ['test2', 3333]]
然后我改用列表推导式,它起作用了:
output = list(map(lambda item: [str(i) for i in item], lst))
output: [['test1', '555'], ['test2', '3333']]
为什么使用 to_str
的第一种方法不起作用?
方法 #1 中的任何地方都没有使用转换后的值 i 并且函数只是 returns 输入
def to_str(item):
result = []
for i in item:
if not isinstance(i, str):
i = str(i)
result.append(i)
return result
您正在尝试修改名为 i
的迭代变量。这根本没有效果,您只是重写了指向列表元素的局部变量的值,而不是更改列表本身。为此,您必须修改每个索引位置的列表元素,如下所示:
def to_str(item):
# iterate over the indexes in the item
for i in range(len(item)):
# we can remove this check, and simply convert everything to str
if not isinstance(item[i], str):
item[i] = str(item[i])
return item
或者我们可以用结果创建一个新列表,而不是覆盖原来的列表(但这等同于使用列表推导,最好使用列表推导):
def to_str(item):
result = []
for element in item:
# we can remove this check, and simply convert everything to str
if not isinstance(element, str):
result.append(str(element))
else:
result.append(element)
return result
此外,关于您的第二种方法:最好避免使用 list
、map
和 lambda
,如果您想要创建一个新列表作为结果直接使用列表理解。这是解决问题的更惯用的方法,同时删除了不必要的字符串检查:
[[str(i) for i in item] for item in lst]
=> [['test1', '555'], ['test2', '3333']]