如何将子列表的所有元素更改为类型?
How can all elements of sublists be changed to a type?
假设我有一个列表列表。子列表本身可以包含子列表。将所有子列表的所有元素转换为特定类型的有效方法是什么?
假设它是这样的乱七八糟的东西:
a = [
1,
2,
3,
[
"a",
"b"
],
[
10,
20,
[
"hello",
"world"
]
],
4,
5,
"hi",
"there"
]
我们的想法是将类似的东西转换成这样:
a = [
"1",
"2",
"3",
[
"a",
"b"
],
[
"10",
"20",
[
"hello",
"world"
]
],
"4",
"5",
"hi",
"there"
]
请注意,我正在寻找处理任意深度子列表的方法。我感觉生成器可以用于此目的,但我不确定如何处理。
最简单的方法是递归执行(您的列表不太可能 所以 嵌套导致问题):
def to_string(L):
return [ str(item) if not isinstance(item, list) else to_string(item) for item in L ]
假设我有一个列表列表。子列表本身可以包含子列表。将所有子列表的所有元素转换为特定类型的有效方法是什么?
假设它是这样的乱七八糟的东西:
a = [
1,
2,
3,
[
"a",
"b"
],
[
10,
20,
[
"hello",
"world"
]
],
4,
5,
"hi",
"there"
]
我们的想法是将类似的东西转换成这样:
a = [
"1",
"2",
"3",
[
"a",
"b"
],
[
"10",
"20",
[
"hello",
"world"
]
],
"4",
"5",
"hi",
"there"
]
请注意,我正在寻找处理任意深度子列表的方法。我感觉生成器可以用于此目的,但我不确定如何处理。
最简单的方法是递归执行(您的列表不太可能 所以 嵌套导致问题):
def to_string(L):
return [ str(item) if not isinstance(item, list) else to_string(item) for item in L ]