正如标题所说我试图在Python中动态命名列表。代码的目的是创建连续字母周围的列表。这是我的代码:
consecutive_duplicates=["a","a","a","a","b","c","c","a","a","d","e","e","e","e","X"]
count=0
name=0
for i in consecutive_duplicates:
if consecutive_duplicates[count]==consecutive_duplicates[count+1] or
consecutive_duplicates[count]==consecutive_duplicates[count-1]:
consecutive_duplicates[name].append(i)
count=count+1
else:
consecutive_duplicates[name+1].append(i)
name=name+1
我不知道如何命名列表。显然这不起作用。什么会使它发挥作用?
我也无法定义动态列表。我该怎么做?
答案 0 :(得分:2)
您可以使用itertools.groupby
:
>>> from itertools import groupby
>>> lis = ["a","a","a","a","b","c","c","a","a","d","e","e","e","e","X"]
>>> [list(g) for k,g in groupby(lis)]
[['a', 'a', 'a', 'a'], ['b'], ['c', 'c'], ['a', 'a'], ['d'], ['e', 'e', 'e', 'e'], ['X']]
而不是创建动态变量,最好使用dict:
>>> dic = { 'lis'+str(i): list(g) for i,(k,g) in enumerate(groupby(lis), 1)}
>>> dic['lis1']
['a', 'a', 'a', 'a']
>>> dic['lis2']
['b']