gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:23:36 25 4
gpt4 key购买 nike

我有以下列表:

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 ' 将在它自己的组中。

我怎样才能达到这个结果?

最佳答案

你需要groupby ,在按 next_dict 值对列表进行排序后:

It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function).

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']]

关于python - 根据元素值将列表划分为多个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42071154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com