所以我有这个字符串列表:
teststr = ['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']
Run Code Online (Sandbox Code Playgroud)
我需要做的是从这个列表中获取包含以下内容的所有元素:
number + "x"
Run Code Online (Sandbox Code Playgroud)
要么
number + "X"
Run Code Online (Sandbox Code Playgroud)
例如,如果我有这个功能
def SomeFunc(string):
#do something
Run Code Online (Sandbox Code Playgroud)
我想得到这样的输出:
2x Sec String
5X fifth
Run Code Online (Sandbox Code Playgroud)
我在StackOverflow中找到了这个函数:
def CheckIfContainsNumber(inputString):
return any(char.isdigit() for char in inputString)
Run Code Online (Sandbox Code Playgroud)
但是这将返回每个具有数字的字符串.
如何扩展功能以获得所需的输出?
所以我在 StackOverflow 中看到了以下关于 Python 中 DFS 算法的帖子(非常有帮助):
这个python代码是否使用深度优先搜索(DFS)来查找所有路径?
我还有一个需要分析的图(以找到两个节点之间的每条可能的路径),但我还需要在那里包括循环。例如,如果我有这样的图表:
graph = {'Start': ['1'],
'1': ['2'],
'2': ['3','End'],
'3': ['2','End']}
Run Code Online (Sandbox Code Playgroud)
我想要以下输出:
Start, 1, 2, 3, End
Start, 1, 2, End
Start, 1, 2, 3, 2, End
Start, 1, 2, 3, 2, 3, End
Run Code Online (Sandbox Code Playgroud)
是否有任何可能的方法来更改以下代码以执行此操作?
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not graph.has_key(start):
return []
paths = []
for node in graph[start]:
if node not in path:
paths += find_all_paths(graph, node, …Run Code Online (Sandbox Code Playgroud)