我想删除并排序我的元素列表
['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'
你可以试试这个:
这也适用于任何数字(3,4位数字等),而不仅仅是2。但需要注意的是,它应该只有一个数字才能工作。这个关于芬德尔查找提供给它的所有模式并返回满足该模式的列表。模式
\d+
表示一个或多个整数。你知道吗在变量所有\u组合中,有二维列表/数组([['elt1','elt11','elt1'],['elt2','elt12','elt1'],['elt3','elt13','elt1'],['elt4','elt14','elt1'],['elt1','elt11','elt2'],…) 你要做的就是:
l=已排序(集合(所有组合),键=lambda x:int(关于芬德尔(r'\d+',x)[0]))
这部分代码适用于您在帖子中提到的列表类型:
结果:['elt1'、'elt2'、'elt3'、'elt9'、'elt19']
将
set
与sorted
一起使用:相关问题 更多 >
编程相关推荐