嗨,我是编程新手。我有问题。我不知道什么是更好的解决方案。问题是这样的..我有一个列表说,
list = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ]
所以我想制作3个列表或一个json对象,实际上有什么可能,请提出更好的选择。这个想法是
list_a = ['123', '643']
list_b = ['890', '234', '123']
list_d = ['432', '678']
或
list_ob = {"a": ["123", "643"], "b": ["890", "234", "123"], "d": ["432", "678"] }
这里,a,b,d只是某些特定字符或可以是单词。请帮帮我。
答案 0 :(得分:1)
很容易做到这一点,您只需要循环检查它是否为alpha,然后将其取为key
。类似于以下内容:
In [92]: key = ''
...: b = {}
...: a = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ]
...: for i in a:
...:
...: if i.isalpha():
...: b[i]=[]
...: key = i
...: else:
...: b[key].append(i)
In [94]: b
Out[94]: {'a': ['123', '643'], 'b': ['890', '234', '123'], 'd': ['432', '678']}
要获得第二个预期结果,只需执行以下操作即可:
In [95]: b.values()
Out[95]: [['123', '643'], ['890', '234', '123'], ['432', '678']]
答案 1 :(得分:0)
这是使用collections
模块的一种方法。
例如:
import collections
l = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ]
res = collections.OrderedDict()
for i in l:
if i.isalpha():
res[i] = []
else:
res[res.keys()[-1]].append(i)
print(res)
输出:
OrderedDict([('a', ['123', '643']), ('b', ['890', '234', '123']), ('d', ['432', '678'])])
或者没有模块
l = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678', "z", "123" ]
res = {}
key = ""
for i in l:
if i.isalpha():
res[i] = []
key = i
else:
res[key].append(i)
print(res)
答案 2 :(得分:0)
您引用的这个json对象在python和许多其他编程语言中称为dictionary
。这是一个结构,其中有一个键和一个与之关联的值。
在这种情况下,更容易处理字典。首先创建一个空字典:
d = dict()
然后,您将创建一个for
循环以填充此词典:
current_key = ""
for e in l:
if e.isalpha(): # If is a letter
current_key = e
d[current_key] = [] # Create an empty list as value
else:
d[current_key].append(e) # Append value
结果:
{'a': ['123', '643'], 'b': ['890', '234', '123'], 'd': ['432', '678']}
答案 3 :(得分:0)
Defaultdict似乎是个不错的选择:
from collections import defaultdict
def split_list(l):
res = defaultdict(list)
current_key = ''
for el in l:
if el.isalpha():
current_key = el
elif current_key:
res[current_key].append(el)
return res
答案 4 :(得分:0)
这是解决方案
{x[0]:x[1].split() for x in re.findall(r"([a-z])([\s*\d+]*)" , " ".join(list))}
{'a':['123','643'],'b':['890','234','123'],'d':['432','678']}
答案 5 :(得分:0)
您可以使用itertools.groupby
:
import itertools
l = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ]
_t = [list(b) for _, b in itertools.groupby(l, key=lambda x:x.isdigit())]
final_result = {_t[i][0]:_t[i+1] for i in range(0, len(_t), 2)}
输出:
{'a': ['123', '643'], 'b': ['890', '234', '123'], 'd': ['432', '678']}