[英]how to replace string elements in nested list with number?
我需要用索引号替换嵌套列表中的字符串元素。 例如,如果我有嵌套列表:
x = ['a', 'b', ['c', ['d', 'e']], 'f']
我想得到:
[1, 2, [3, [4, 5]], 6]
我知道我应该做一个递归 function 并使用
isinstance()
这没有用:
def indexer(f, lst):
return [indexer(f, x) if isinstance(x, list) else x.index() for x in lst]
这是使用递归的一种方法。
前任:
def get_index(lst, c=1):
result = []
for i in lst:
if isinstance(i, list):
r, c = get_index(i, c)
result.append(r)
else:
result.append(c)
c += 1
return result, c
x = ['a', 'b', ['c', ['d', 'e']], 'f']
result, _ = get_index(x)
print(result)
Output:
[1, 2, [3, [4, 5]], 6]
尝试这个:
x = ['a', 'b', ['c', ['d', 'e']], 'f']
def get_index(c):
return ord(c) - ord('a') + 1
def get_reversed_index(i):
return chr(i - 1 + ord('a'))
def indexer(lst):
return [indexer(x) if isinstance(x, list) else get_index(x) for x in lst]
def reverse_indexer(lst):
return [reverse_indexer(x) if isinstance(x, list) else get_reversed_index(x) for x in lst]
y = indexer(x)
z = reverse_indexer(y)
print(y)
print(z)
Output:
[1, 2, [3, [4, 5]], 6]
['a', 'b', ['c', ['d', 'e']], 'f']
你可以试试这样的
def list_to_index(old_list, starting_index = None):
new_list = []
index = starting_index if starting_index else 0
for item in old_list:
if isinstance(item, list):
new_item = list_to_index(item, index)
new_list.append(new_item[0])
index = new_item[1]
else:
new_list.append(index + 1)
index += 1
return [new_list, index]
x = ['a', 'b', ['c', ['d', 'e']], 'f']
print(list_to_index(x)[0])
## Expected output
## [1, 2, [3, [4, 5]], 6]
使用内置copy.deepcopy
和itertools.count
魔法:
(输入初始列表没有变异)
from itertools import count
from copy import deepcopy
def indexer(lst):
counter = count(1)
def _visit(lst):
for i, v in enumerate(lst):
if isinstance(v, list):
_visit(v)
else:
lst[i] = next(counter)
return lst
return _visit(deepcopy(lst))
x = ['a', 'b', ['c', ['d', 'e']], 'f']
print(indexer(x))
output:
[1, 2, [3, [4, 5]], 6]
另一个测试用例:
x = [['g', 'h'], 'a', [['i', 'k'], 'l'], ['m', 'p', ['o']], 'b', ['c', ['d', 'e']], 'f']
print(indexer(x))
output:
[[1, 2], 3, [[4, 5], 6], [7, 8, [9]], 10, [11, [12, 13]], 14]
使用迭代器的更短的递归解决方案:
import itertools
c = itertools.count(1)
def to_int(d):
return [to_int(i) if isinstance(i, list) else next(c) for i in d]
print(to_int(['a', 'b', ['c', ['d', 'e']], 'f']))
Output:
[1, 2, [3, [4, 5]], 6]
这是一个可爱的递归方法,允许您将 map 任何 function 到嵌套列表,然后使用defaultdict
技巧来索引元素,假设您希望相同的元素由相同的索引表示:
from collections import defaultdict
def map_nested(fnc, lst):
if isinstance(lst, list):
return [map_nested(fnc, sub) for sub in lst]
return fnc(lst)
d = defaultdict(lambda: len(d))
map_nested(d.__getitem__, ['a', 'b', ['c', ['d', 'e']], 'f', 'a'])
# [0, 1, [2, [3, 4]], 5, 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.