Python:如何在 python 中反转对象字符串函数
Python: How to reverse an objects string function in python
例如,我有一个 class 墙(没有 init)
如果a = Wall()
和str(a)
输出:'#'
如果我有一个包含'####'的字符串
我怎样才能将该字符串变成一个列表,其中包含 class 对象的名称,如下所示:
[Wall(), Wall(), Wall(), Wall()]
您可以将 list comprehension 与过滤子句一起使用:
walls = [Wall() for char in string
if char == '#']
您应该创建一个明确的映射字典,告诉字符串中每个字符的含义。
wall = object()
mapping = {
"#": wall
}
string = '####'
result = [mapping[ch] for ch in string]
例如,我有一个 class 墙(没有 init)
如果a = Wall()
和str(a)
输出:'#'
如果我有一个包含'####'的字符串
我怎样才能将该字符串变成一个列表,其中包含 class 对象的名称,如下所示:
[Wall(), Wall(), Wall(), Wall()]
您可以将 list comprehension 与过滤子句一起使用:
walls = [Wall() for char in string
if char == '#']
您应该创建一个明确的映射字典,告诉字符串中每个字符的含义。
wall = object()
mapping = {
"#": wall
}
string = '####'
result = [mapping[ch] for ch in string]