gpt4 book ai didi

python - 从字典和列表中删除重复元素并排序元素

转载 作者:行者123 更新时间:2023-12-01 01:13:39 25 4
gpt4 key购买 nike

我想删除并排序我的元素列表

['elt9', 'elt19', 'elt1', 'elt2', 'elt3','elt9','elt2']

并得到

['elt1', 'elt2', 'elt3', 'elt9', 'elt19']

这是我的全部代码:

import itertools as it
import re
from collections import OrderedDict
from itertools import chain

L1 = ['elt1', 'elt2', 'elt3', 'elt4', 'elt5', 'elt6', 'elt9']
L2 = [['elt1','elt11'],['elt2','elt12'],['elt3','elt13'], ['elt4','elt14']]

def generate_combinations(L):
L_com = []
for r in range(1, len(L)+1):
L_com += list(it.combinations(L, r))

all_combination= []
for i in L_com:
for j in L2:
all_combination.append(j+list(i))

l = sorted(set(all_combination), key = lambda x : int(re.findall(r'\d+', x)[0]))
with open('combinations.txt', 'w') as file_handler:
for item in l:
file_handler.write("{}\n".format(item))

if __name__ == "__main__":
generate_combinations(L1)

我遇到了这个错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-49-e0b599cc4158> in <module>()
1 if __name__ == "__main__":
----> 2 generate_combinations(L1)

<ipython-input-45-81ef5db3553e> in generate_combinations(L1)
21
22 #sorted(set(all_combination), key=lambda x: int(x[3:]))
---> 23 l = sorted(set(all_combination), key = lambda x : int(re.findall(r'\d+', x)[0]))
24
25 with open('combinations.txt', 'w') as file_handler:

TypeError: unhashable type: 'list'

最佳答案

setsorted结合使用:

l = ['elt9', 'elt19', 'elt1', 'elt2', 'elt3','elt9','elt2']
sorted(set(l), key=lambda x: int(x[3:]))

['elt1', 'elt2', 'elt3', 'elt9', 'elt19']

关于python - 从字典和列表中删除重复元素并排序元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590485/

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