考虑以下Python列表:
my_list = [[0], [1], [2], [3], [4], [5], [6, 2], [7, 6, 4, 3], [8, 6, 3], [9], [10, 4, 3], [11], [12, 9], [13, 11, 12]]
my_list
的每个元素都是以my_list
中的索引开头的列表,其他值小于第一个,因此也显示为某个先前列表的第一个元素。
例如,my_list[8]
为[8, 6, 3]
(并且每个人都知道6,3 < 8
)。
我希望在可能的情况下进行以下替换:如果s
中的my_list
包含元素s_i
,那么r
中的某些元素my_list
{}为[s_i, a, b, c]
(或更长),将s_i
中的s
替换为s_i, a, b, c
(或更多)。
例如,[13, 11, 12]
中my_list
代替[13, 11, 12, 9]
(也可以为其他元素完成) 我想[12, 9]
1}}因为my_list
也在[9, 4]
。
但请注意,如有必要,此程序应以递归方式完成。
例如,假设my_list
位于[13, 11, 12, 9, 4]
,则结果应为[6, 2]
。
或者,由于my_list
位于[7, 6, 4, 3]
,因此也应对[8, 6, 3]
和while
进行此类替换。
对不起,如果不清楚我需要什么。我认为定义一些函数并在// Store this as a property if you're searching a lot.
let digitsCharacterSet = NSCharacterSet.decimalDigits
let filteredResults = completer.results.filter { result in
if result.title.rangeOfCharacter(from: digitsCharacterSet) != nil {
return false
}
if result.subtitle.rangeOfCharacter(from: digitsCharacterSet) != nil {
return false
}
return true
}
中调用它可能是一种利润。
答案 0 :(得分:1)
my_list = [[0], [1], [2], [3], [4], [5], [6], [7, 6, 4, 3], [8, 6, 3], [9], [10, 4, 3], [11], [12, 9], [13, 11, 12]]
def by_first(l):
d = {}
for i in l:
if len(i) > 1:
d.setdefault(i[0], []).append(i)
return d
index = by_first(my_list)
def dfs(item):
for p in index.get(item[-1], []):
q = item + p[1:]
yield q
for v in dfs(q):
yield v
for l in my_list:
for p in dfs(l):
print p
索引包含:
{7: [[7, 6, 4, 3]],
8: [[8, 6, 3]],
9: [[9, 4]],
10: [[10, 4, 3]],
12: [[12, 9]],
13: [[13, 11, 12]]}
没有[9, 4]
打印:
[13, 11, 12, 9]
如果我们添加[9, 4]
:
[9, 4]
[12, 9, 4]
[13, 11, 12, 9]
[13, 11, 12, 9, 4]
这些项目至少附加了一个其他项目。 [9, 4]
就在那里,因为它附加到[9]
看起来你可能只想要最长的。
要获得与最长项目数相同的列表之一,请执行以下操作:
def find():
for l in my_list:
#yield l
for p in dfs(l):
yield p
print max(find(), key=len)
如果您希望包含初始列表,请取消注释行yield l
。