根据元素值将列表分为多个列表

时间:2017-02-06 15:16:13

标签: python

我有以下列表:

initial_list = [['B', 'D', 'A', 'C', 'E']]

在列表的每个元素上,我应用一个函数并将结果放在字典中:

for state in initial_list:
    next_dict[state] = move([state], alphabet)

这给出了以下结果:

next_dict = {'D': ['E'], 'B': ['D'], 'A': ['C'], 'C': ['C'], 'E': ['D']}

我想要做的是根据他们的内容将键与initial_list分开 next_dict字典中的值,基本上将第一个列表的元素分组到next_dict中具有相同值的元素:

new_list = [['A', 'C'], ['B', 'E'], ['D']]

'A'和'C'将保持在同一组中,因为它们具有相同的值'C','B'和'D'也将共享同一组,因为它们的值为'D'然后'D' '将成为它自己的小组。

如何实现这一结果?

5 个答案:

答案 0 :(得分:4)

next_dict值排序后,您需要groupby

  

每次键值产生一个中断或新组   功能变化(这就是为什么通常需要排序   数据使用相同的键功能)。

from itertools import groupby

initial_list = ['B', 'D', 'A', 'C', 'E']

def move(letter):
    return {'A': 'C', 'C': 'C', 'D': 'E', 'E': 'D', 'B': 'D'}.get(letter)
sorted_list = sorted(initial_list, key=move)
print [list(v) for k,v in groupby(sorted_list, key=move)]
#=> [['A', 'C'], ['B', 'E'], ['D']]

答案 1 :(得分:3)

实现此目标的最简单方法是将itertools.groupby与密钥dict.get一起使用为:

>>> from itertools import groupby
>>> next_dict = {'D': ['E'], 'B': ['D'], 'A': ['C'], 'C': ['C'], 'E': ['D']}
>>> initial_list = ['B', 'D', 'A', 'C', 'E']

>>> [list(i) for _, i in groupby(sorted(initial_list, key=next_dict.get), next_dict.get)]
[['A', 'C'], ['B', 'E'], ['D']]

答案 2 :(得分:3)

我不确定这是您想要的,但您可以根据next_dict中的值对值进行分组:

>>> next_dict = {'D': 'E', 'B': 'D', 'A': 'C', 'C': 'C', 'E': 'D'}

>>> # external library but one can also use a defaultdict.
>>> from iteration_utilities import groupedby  

>>> groupings = groupedby(['B', 'D', 'A', 'C', 'E'], key=next_dict.__getitem__)
>>> groupings
{'C': ['A', 'C'], 'D': ['B', 'E'], 'E': ['D']}

然后将其转换为其值列表:

>>> list(groupings.values())
[['A', 'C'], ['D'], ['B', 'E']]

将所有内容组合成一个单行(不是真的推荐,但很多人更喜欢):

>>> list(groupedby(['B', 'D', 'A', 'C', 'E'], key=next_dict.__getitem__).values())
[['A', 'C'], ['D'], ['B', 'E']]

答案 3 :(得分:2)

我们可以使用字典映射对列表进行排序,然后使用itertools.groupby组成组。我在这里做的唯一修改就是让你的初始列表成为一个实际的平面列表。

>>> from itertools import groupby
>>> initial_list = ['B', 'D', 'A', 'C', 'E']
>>> next_dict = {'D': ['E'], 'B': ['D'], 'A': ['C'], 'C': ['C'], 'E': ['D']}
>>> s_key = lambda x: next_dict[x]
>>> [list(v) for k, v in groupby(sorted(initial_list, key=s_key), key=s_key)]
[['A', 'C'], ['B', 'E'], ['D']]

答案 4 :(得分:2)

试试这个:

with open("dictionary.txt","r") as file: 
        words=[]
        for line in file: #loop through every line to get all words
            words.append(line)

for word in words:
    if sum(letter in "aeiou" for letter in word)==1 and "s" not in word and len(word)==7:
        print(word)

或者这个:

next_next_dict = {}
for key in next_dict:
    if next_dict[key][0] in next_next_dict:
        next_next_dict[next_dict[key][0]] += key
    else:
        next_next_dict[next_dict[key][0]] = [key]
new_list = next_next_dict.values()