d3p*_*3pd -1 python types list generator sublist
假设我有一份清单清单.子列表本身可以包含子列表.将所有子列表的所有元素转换为特定类型的有效方法是什么?
让我们说它像这样凌乱:
a = [
1,
2,
3,
[
"a",
"b"
],
[
10,
20,
[
"hello",
"world"
]
],
4,
5,
"hi",
"there"
]
Run Code Online (Sandbox Code Playgroud)
我的想法是将类似的内容转换为:
a = [
"1",
"2",
"3",
[
"a",
"b"
],
[
"10",
"20",
[
"hello",
"world"
]
],
"4",
"5",
"hi",
"there"
]
Run Code Online (Sandbox Code Playgroud)
请注意,我正在寻找处理任意深度的子列表的方法.我有一种感觉,可以使用发电机,但我不知道如何处理这个问题.
最简单的方法是递归地做到这一点(列表不可能是这样的嵌套,以引起问题):
def to_string(L):
return [ str(item) if not isinstance(item, list) else to_string(item) for item in L ]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |