我需要用索引号替换嵌套列表中的字符串元素。例如,如果我有嵌套列表:
x = ['a', 'b', ['c', ['d', 'e']], 'f']
我想得到:
[1, 2, [3, [4, 5]], 6]
我知道我应该做一个递归函数并且也要使用
isinstance()
这不起作用:
def indexer(f, lst):
return [indexer(f, x) if isinstance(x, list) else x.index() for x in lst]
答案 0 :(得分:1)
这是使用递归的一种方法。
例如:
# A tibble: 1 x 5
Question_Value_1 Question_Value_2 Question_Value_3 Question_Value_4 Question_Value_5
<chr> <chr> <chr> <chr> <chr>
1 Value_1 Value_2 Value_3 Value_4 Value_5
输出:
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)
答案 1 :(得分:0)
尝试一下:
a > 5
输出:
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)
答案 2 :(得分:0)
您可以尝试这样的事情
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]
答案 3 :(得分:0)
内置yield
和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))
另一个测试用例:
[1, 2, [3, [4, 5]], 6]
输出:
x = [['g', 'h'], 'a', [['i', 'k'], 'l'], ['m', 'p', ['o']], 'b', ['c', ['d', 'e']], 'f']
print(indexer(x))
答案 4 :(得分:0)
使用迭代器的更短递归解决方案:
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']))
输出:
[1, 2, [3, [4, 5]], 6]
答案 5 :(得分:0)
这是一种可爱的递归方法,允许您将任何函数映射到嵌套列表,然后使用defaultdict
技巧为元素建立索引,假设您希望相同的元素由相同的索引表示:< / p>
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]