English 中文(简体)
递回循环到字符串列表以检索字符串组
原标题:Recursively iterate over list of strings to retrieve groups of strings
如下列表 : 插入 = [“ arg1: ”、“ 列表 ”, “ 列表 ”, “ args ”, “ args ”, “ arg2 ”, “ [“ arg1 ”, “ 列表 ”, “ arg2 ”, “ [“ arg1 ”,, “ 列表 ”, “ args, ”, “ arg2, ”, “ 其它 ”, “ 列表 ”, “ 其他 ”, “ “ 列表 ” ”, “ [ “ 列表 ”, “ 列表 ”, “ 其它示例 : “ 列表 ”, “ 列表 ” 。 其他示例是 : 插入 “ ”, “ 测试 ”, “ 1, “ 2 ”, “ 3 ” [ list”, “ ”, “ list”, [, “, “ list”,, “ 3,,, “ list”,, “,,,, “ list”, “,
最佳回答
You don t need any recursion, just take the items one by one, if you have a colon change the key. Use dict.sedefault as helper to initialize the empty lists: inp = [ arg1: , list , of , args , arg2: , other , list ] out = {} key = None # default key for item in inp: if item.endswith( : ): key = item.removesuffix( : ) continue out.setdefault(key, []).append(item) Output: { arg1 : [ list , of , args ], arg2 : [ other , list ]}
问题回答
I don t believe there s a "pythonic" way of doing this, without using some lambdas which would make the code some what unreadable. But as you point out, it s pretty straight forward to implement this with a loop and "exploiting" the fact that dict s are mutable: inp = ["arg1:", "list", "of", "args", "arg2:", "other", "list"] result = {} reference_point = result for item in inp: if item.endswith( : ): if (item := item.rstrip( : )) not in result: result[item] = [] reference_point = result[item] else: reference_point.append(item) print(result) There s some edge cases that I did not take into account, mainly because you did not specify what should happen in such cases. Like what if the input starts with a "value" and not a item that ends with :. But this should give you a general idea of how you could solve it.
You re right, it probably should not be a one-liner. out = {s[:-1]: (v := []) for s in inp if s[-1:] == : or v.append(s)} Attempt This Online!
One straight forward way is to just write the exact algorithm you described. def foo(xs: list[str]) -> dict[str, list[str]]: d = {} for x in xs: if x[-1] == : : d[x[:-1]] = l = [] else: l.append(x) return d inp = ["test:", "one", "help:", "two", "three", "four"] out = {"test": ["one"], "help": ["two", "three", "four"]} assert foo(inp) == out inp = ["one:", "list", "two:", "list", "list", "three:", "list", "list", "list"] out = {"one": ["list"], "two": ["list", "list"], "three": ["list", "list", "list"]} assert foo(inp) == out I personally don t prefer this, as it s very imperative, and not pythonic or functional in nature. I ll update the answer, if I manage to write a short functional one.
Here s a simple function that handles lists that are in order and start with a key. It works for your example cases and handles the argument of the function with a default empty list (an empty list will return an empty dict). def convertListToDict(argList = []): returnDict = {} newKey = None for arg in argList: if arg[-1] == ":": newKey = arg[:-1] returnDict[newKey] = [] elif newKey: returnDict[newKey].append(arg) return returnDict
While @mozway s solution works, it unnecessarily incurs the overhead of a dict lookup and the instantiation of a new list for every iteration where the item does not end with :. You can instead keep a reference to the last-created list and simply append new items to the referenced list: inp = ["arg1:", "list", "of", "args", "arg2:", "other", "list"] out = {} for i in inp: if i.endswith( : ): out[i.removesuffix( : )] = lst = [] else: lst.append(i) out becomes: { arg1 : [ list , of , args ], arg2 : [ other , list ]} Demo here
import itertools L = ["arg1:", "list", "of", "args", "arg2:", "other", "list"] answer = {} key = None for k, group in itertools.groupby(L, lambda s: s.endswith(":")): if k: key = list(group)[0].rstrip(":") else: answer[key] = list(group) Result: In [313]: answer Out[313]: { arg1: : [ list , of , args ], arg2: : [ other , list ]}




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签